我有一个带有该代码的自定义用户控件:
public partial class AudioControl : UserControl
{
public AudioControl()
{
InitializeComponent();
Value = 0.1;
DataContext = this;
}
public event RoutedPropertyChangedEventHandler<double> ValueChanged = delegate { };
public int TextWidth
{
get { return (int)GetValue(TextWidthProperty); }
set { SetValue(TextWidthProperty, value); }
}
public int SliderWidth
{
get { return (int)GetValue(SliderWidthProperty); }
set { SetValue(SliderWidthProperty, value); }
}
public string Header
{
get { return (string)GetValue(TextBlock.TextProperty); }
set { SetValue(TextBlock.TextProperty, value); }
}
//public double Value
//{
// get { return (double)GetValue(Slider.ValueProperty); }
// set { SetValue(Slider.ValueProperty, value); }
//}
public double Value
{
get {
return (double)GetValue(ValueProperty);
}
set {
SetValue(ValueProperty, value);
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double), typeof(AudioControl), new UIPropertyMetadata(0));
public static readonly DependencyProperty TextWidthProperty =
DependencyProperty.Register("TextWidth", typeof(int), typeof(AudioControl), new UIPropertyMetadata(0));
public static readonly DependencyProperty SliderWidthProperty =
DependencyProperty.Register("SliderWidth", typeof(int), typeof(AudioControl), new UIPropertyMetadata(0));
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
ValueChanged(this, e);
}
}
而这个 XAML:
<UserControl x:Class="Controller.Audio.AudioControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:Audio="clr-namespace:Controller.Audio"
mc:Ignorable="d"
d:DesignHeight="23" d:DesignWidth="500" x:Name="audioControl">
<UserControl.Resources>
<Audio:DoubleToIntConverter x:Key="doubleToInt"/>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding TextWidth}"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="{Binding SliderWidth}"/>
</Grid.ColumnDefinitions>
<Label x:Name="txtBlock" Margin="0,0,10,0">
<Binding Path="Header"/>
</Label>
<Label Grid.Column="1" Content="{Binding ElementName=slider, Path=Value, Converter={StaticResource doubleToInt}}"/>
<Slider x:Name="slider" Grid.Column="2" Style="{StaticResource Office2010SilverSliderStyle}"
Value="{Binding Path=Value, ElementName=audioControl}" Minimum="0.0" Maximum="1.0" LargeChange="0.25" TickFrequency="0.01" ValueChanged="Slider_ValueChanged"/>
</Grid>
因此,如果我启动它,我会得到一个异常,即值绑定的某些东西是错误的。我还尝试了注释版本(价值属性)。也不例外,但如果我设置该属性的值,我的滑块不会改变。
有谁知道为什么?我从来没有做过这样的事情:(