gpt4 book ai didi

c# - 从 UserControl 的 DependencyProperty 绑定(bind)不起作用

转载 作者:行者123 更新时间:2023-12-03 10:55:16 26 4
gpt4 key购买 nike

我有一个 UserControl一个DependencyProperty设置在代码隐藏 (我想这可能是我的问题的根源,但仍然不知道该怎么办):

用户控制

 public partial class MyControl
{
public MyControl()
{
InitializeComponent();
}

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyControl),
new FrameworkPropertyMetadata("",FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); InvokePropertyChanged(new PropertyChangedEventArgs("Text"));}
}

public static string GetText(DependencyObject obj)
{
return (string)obj.GetValue(TextProperty);
}

public static void SetText(DependencyObject obj, string value)
{
obj.SetValue(TextProperty, value);
}

private void ChangeText()
{
Text="some value";
}
}

在我的 View.xaml 中,我像这样使用这个控件:
 <MyControl Text="{Binding Text, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

我的 ViewModel 中的 Text 属性:
 private string _text;
public string Text
{
get { return _text; }
set { _text= value; InvokePropertyChanged(new PropertyChangedEventArgs("Text"));}
}

问题:
ViewModel 中的 Text 属性永远不会更新;当使用像 TextBox 这样的常规控件绑定(bind)时,一切都很完美;如果我在 XAML 中设置 Text,则 UserControl 的 Text 属性会更新。
我做错了什么?

更新
我的问题是我在 MyControl 上明确设置了 DataContext。

最佳答案

问题在于您的绑定(bind):

Text="{Binding Text, RelativeSource={RelativeSource Self}, 
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"

Text属性在您的 ViewModel 中,但您通过使用 RealtiveSource 指向自身来引用自身。因此,它将 Text DP 与自身绑定(bind)。

如果您设置了 DataContext您的控制,它将自动继承 DataContext从 parent 。所以,你不需要 RelativeSource一点也不。

它应该是:
Text="{Binding Text}"

多一点(但与您的问题无关) :
  • 由于您的目标是在控制范围内使用此属性,因此请使用普通 DP 而不是附加属性。
  • 由于在注册时,您已将其设置为默认绑定(bind) TwoWay。无需在绑定(bind)时明确执行此操作。
  • 从 DP 包装器 setter 中删除 InvokePropertyChanged 调用。不会从 XAML 调用 Setter,并且 DP 已经知道 PropertyChanged。


  • 更新

    万一 DataContextMyControl设置为另一个类的实例,上述方法将搜索 Text MyControl DataContext 中的属性。

    您可以像这样传递父控件(在您的情况下为 StackPanel)的 DataContext:
    Text="{Binding DataContext.Text, RelativeSource={RelativeSource 
    Mode=FindAncestor, AncestorType=StackPanel}}"

    关于c# - 从 UserControl 的 DependencyProperty 绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22041630/

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