M. *_*ley 8 data-binding wpf togglebutton
我有一个ToggleButton与它的IsChecked属性绑定到使用单向绑定属性.
<ToggleButton
Command="{Binding Path=SomeCommand}"
IsChecked="{Binding Path=SomeProperty, Mode=OneWay}" />
Run Code Online (Sandbox Code Playgroud)
该SomeCommand切换布尔SomeProperty值,一个PropertyChanged事件引发的SomeProperty.
如果我更改SomeProperty了我的viewmodel,ToggleButton则会正确压下.但是,如果我单击该ToggleButton绑定似乎丢失,并且不再根据值来检查该按钮SomeProperty.关于如何解决这个问题的任何想法?
Ale*_*x_P 12
有一种简单而优雅的方法来解决原始海报的问题 - 将ToggleButton的IsChecked属性替换为可附加属性,该属性将在其更改处理程序中设置按钮的IsChecked:
namespace TBFix
{
public class TBExtender
{
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.RegisterAttached("IsChecked",
typeof(bool),
typeof(TBExtender),
new PropertyMetadata(OnChanged));
public static bool GetIsChecked(DependencyObject obj)
{
return (bool)obj.GetValue(IsCheckedProperty);
}
public static void SetIsChecked(DependencyObject obj, bool value)
{
obj.SetValue(IsCheckedProperty, value);
}
private static void OnChanged(DependencyObject o,
DependencyPropertyChangedEventArgs args)
{
ToggleButton tb = o as ToggleButton;
if (null != tb)
tb.IsChecked = (bool)args.NewValue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后XAML将如下所示:
<ToggleButton Command="{Binding Path=SomeCommand}"
TBFix:TBExtender.IsChecked="{Binding Path=SomeProperty,
Mode=OneWay}" />
Run Code Online (Sandbox Code Playgroud)
编辑:OP解决方案不起作用,因为当按下按钮时,IsChecked属性在代码中设置(这是MS实现ToggleButton控件的方式) - 设置属性将从中删除绑定,因此它将停止工作.
通过使用附加属性,我们可以克服这个问题,因为它从未在代码中赋值,因此绑定保持不变.
使用单向数据绑定时,这是设计使然。将附加的属性PresentationTraceSources.TraceLevel = High添加到绑定中,您将看到断开连接的时间。此链接也描述了问题(不提供任何解决方案):在WPF中调试数据绑定
我通常解决的方法是使用命令进行用户交互,并使用后面的代码来更改控件外观,因为某些属性已更改。
| 归档时间: |
|
| 查看次数: |
8704 次 |
| 最近记录: |