我认为这对于世界粮食计划署的中间人来说是一个初学者的问题 . 我有一个用户控件,它使用两个普通按钮充当radiobutton :(按钮改变颜色以显示当前选择)
<UserControl x:Class="UI.UserControls.RadioUC" Loaded="UserControl_Loaded">
<Stackpanel DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<TextBlock Text="{Binding Path=Title}"/>
<Button x:Name="BtnYes" Content="YES" Click="BtnYes_Click">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding Command}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button x:Name="BtnNo" Content="NO" Click="BtnNo_Click">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding Command}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Stackpanel>
</UserControl>
代码隐藏包括2个依赖属性Title&IsYes . 使用单击事件单击按钮时,将修改IsYes属性 .
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(RadioUC),
new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty IsYesProperty = DependencyProperty.Register("IsYes", typeof(bool), typeof(RadioUC),
new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public bool IsYes {
get { return (bool)GetValue(IsYesProperty); }
set { SetValue(IsYesProperty, value); }
}
public String Title {
get { return (String)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
private void BtnYes_Click(object sender, RoutedEventArgs e)
{
IsYes = true;
//BtnYes.Background = new SolidColorBrush(Colors.ForestGreen);
//BtnNo.Background = new SolidColorBrush(Colors.Gray);
}
private void BtnNo_Click(object sender, RoutedEventArgs e)
{
IsYes = false;
//BtnNo.Background = new SolidColorBrush(Colors.ForestGreen);
//BtnYes.Background = new SolidColorBrush(Colors.Gray);
}
最后我如何使用它:
<uc:RadioUC Title="Is it YES" IsYes="{Binding IsLocalYes, Mode=TwoWay}"/>
单独单击按钮时,usercontrol的IsYes属性将成功修改 . 没有问题 . 问题是当我在usercontrol的托管窗口中以编程方式修改IsLocalYes时,此更改不会传播到usercontrol中 . 所以问题是当IsLocalYes属性发生变化时,如何修改usercontrol的IsYes属性?
1 回答
而不是创建自己的
UserControl
,为了你想要实现的目标,最好使用ToggleButton
并更改ControlTemplate
/Style
.另请阅读article
Solution:
切换按钮样式:
像这样用它: