gpt4 book ai didi

c# - 数据绑定(bind)到附加属性

转载 作者:行者123 更新时间:2023-12-03 10:27:06 24 4
gpt4 key购买 nike

我尝试使用 Attached Property到我在 .NET 3.5 中的控件之一。这个想法是在特定操作之后需要集中控制。我想将此属性绑定(bind)到 ViewModel 上的一个值,以便可以根据需要更改该属性(即,当我更改 ViewModel 上的值时,它会更新附加属性中的值)。

附楼

class FocusProperty : DependencyObject
{
public static DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached ("IsFocused",
typeof (bool),
typeof (FocusProperty),
new UIPropertyMetadata (false, OnIsFocusedChanged));

public static bool GetIsFocused (DependencyObject DObject)
{
return (bool)DObject.GetValue (IsFocusedProperty);
}

public static void SetIsFocused (DependencyObject DObject, bool Value)
{
DObject.SetValue (IsFocusedProperty, Value);
}

public static void OnIsFocusedChanged (DependencyObject DObject, DependencyPropertyChangedEventArgs Args)
{
UIElement Control = DObject as UIElement;
bool NewValue = (bool)Args.NewValue;
bool OldValue = (bool)Args.OldValue;

// REMOVE TODO
System.Windows.MessageBox.Show ("OI");

if (NewValue && !OldValue && !Control.IsFocused)
{
Control.Focus ();
}
}
}

在 XAML 中,它是这样使用的:
a:FocusProperty.IsFocused="{Binding Path=IsListFocused}

在哪里 IsListFocused是 ViewModel 上的 bool 属性:
public bool IsListFocused
{
get { return isListFocused_; }
set
{
isListFocused_ = value;
OnPropertyChanged ("IsFocused");
}
}

但它不起作用 - 当 IsListFocused 发生更改时,MessageBox 不会按预期显示。

我一直在寻求有关该主题的帮助,但似乎附加属性不是很多使用的东西,因此没有太多的支持方式。

我的问题是: 为什么上面的代码片段没有按预期工作?

最佳答案

IsListFocused View 模型中的属性 setter ,替换

OnPropertyChanged("IsFocused");

经过
OnPropertyChanged("IsListFocused");

关于c# - 数据绑定(bind)到附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36690378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com