我试图实现一个名为 UserControlParityTypeSelect
的包含两个 RadioButton - Odd
& Even
,并且 UserControl 将调用一个 DependencyProperty ParityType
,它将在双向绑定中使用。这个想法很简单 - 如果Odd
选择ParityType
应该返回 1,如果Even
选择ParityType
应该返回 0。
这是代码 -
XAML(用户控件):
<StackPanel Orientation="Horizontal">
<RadioButton Name="rdoOdd" Content="Odd" Margin="5" Checked="rdoOdd_CheckedChnaged" Unchecked="rdoOdd_CheckedChnaged" />
<RadioButton Name="rdoEven" Content="Even" Margin="5"/>
</StackPanel>
代码隐藏(用户控件):
public partial class ParityTypeSelect : UserControl
{
//Some Code
static ParityTypeSelect()
{
FrameworkPropertyMetadata parityTypeMetaData =
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnParityTypeChanged),
new CoerceValueCallback(CoerceParityTypeValue));
ParityTypeProperty = DependencyProperty.Register("ParityType", typeof(int?), typeof(ParityTypeSelect),
parityTypeMetaData,
new ValidateValueCallback(ValidateParityTypeValue));
}
public static readonly DependencyProperty ParityTypeProperty;
public int? ParityType
{
get { return (int?)GetValue(ParityTypeProperty); }
set { SetValue(ParityTypeProperty, value); }
}
private static void OnParityTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ParityTypeSelect select = (ParityTypeSelect)d;
int? newValue = (int?)e.NewValue;
if (newValue != null && newValue <= 1)
{
if (newValue == 1)
select.rdoOdd.IsChecked = true;
else
select.rdoEven.IsChecked = true;
}
else
return;
}
private void rdoOdd_CheckedChnaged(object sender, RoutedEventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.IsChecked != null)
{
if (radioButton.IsChecked.Value)
SetValue(ParityTypeProperty, 1);
else
SetValue(ParityTypeProperty, 0);
}
}
//Some more Code
}
XAML(消费者):
<StackPanel>
<aucl:ParityTypeSelect ParityType="{Binding Path=Format.FisrtBitType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
...而且它正在工作。但问题是,这是我第一次实现 DependencyProperty。所以我有点担心我是否做得对。我是否OnParityTypeChanged
以正确的方式使用该方法?使用rdoOdd_CheckedChnaged
事件处理程序设置属性值可以吗?有没有更好或更合适的方法来完成整个实现?我一直期待高质量的编码。因此,任何建议,改进建议,来自WPF
人们的评论将不胜感激。