如何解决根据视图模型中的布尔属性关注DecimalUpDowns
我想基于DecimalUpDown
上的布尔属性来集中多个ViewModel
以下是XAML。例如,如果我将IsFocused
上的DecimalUpDown
绑定到我的视图模型上的一个属性,那么它将不起作用。我知道可以通过创建行为来实现,但是我还不知道该怎么做。
//This is DecimalUpDown1
<DecimalUpDown IsFocused={Binding IsDUD1Invalid} />
//This is DecimalUpDown2
<DecimalUpDown IsFocused={Binding IsDUD2Invalid} />
private bool _isDUD1Invalid = false;
public bool IsDUD1Invalid
{
get { return _isDUD1Invalid; }
set
{
_isDUD1Invalid = value;
PropertyChanged(this,new PropertyChangedEventArgs(nameof(IsDUD1Invalid)));
}
}
private bool _isDUD2Invalid = false;
public bool IsDUD2Invalid
{
get { return _isDUD2Invalid; }
set
{
_isDUD2Invalid = value;
PropertyChanged(this,new PropertyChangedEventArgs(nameof(IsDUD2Invalid)));
}
}
private void SampleCommand1()
{
//Focus DecimalUpDown1
IsDUD1Invalid = true;
}
private void SampleCommand2()
{
//Focus DecimalUpDown1
IsDUD2Invalid = true;
}
当然,它一次只能聚焦一个DecimalUpDown
。我想避免视图中使用特定的外部触发器来设置焦点,例如单击按钮。我希望它可以通过任何更改boolean属性值的方法来触发。预先谢谢你。
解决方法
IsFocused
属性为只读,因此您不能以这种方式绑定它。但是,您可以创建一个附加属性,以在条件为True
时将键盘焦点赋予UI元素。
public static class ConditionalFocusProperties
{
public static readonly DependencyProperty ConditionProperty = DependencyProperty.RegisterAttached(
"Condition",typeof(bool),typeof(ConditionalFocusProperties),new PropertyMetadata(OnConditionChanged));
public static bool GetCondition(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(ConditionProperty);
}
public static void SetCondition(DependencyObject dependencyObject,bool value)
{
dependencyObject.SetValue(ConditionProperty,value);
}
private static void OnConditionChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
if (!(d is UIElement uiElement))
return;
if ((bool) e.NewValue)
Keyboard.Focus(uiElement);
// Uncomment,if you want to remove the focus when "Condition" turns "false".
/*
else if (uiElement.IsKeyboardFocusWithin)
Keyboard.ClearFocus();
*/
}
}
您可以像这样在XAML中附加和绑定属性,例如IsDUD1Invalid
。
<DecimalUpDown local:ConditionalFocusProperties.Condition="{Binding IsDUD1Invalid}"/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。