gpt4 book ai didi

c# - WPF UserControl绑定(bind)问题

转载 作者:行者123 更新时间:2023-11-30 14:39:21 25 4
gpt4 key购买 nike

我喜欢创建一个拥有自己的 Header 属性的 UserControl。

public partial class SomeClass: UserControl, INotifyPropertyChanged
{
public SomeClass()
{
InitializeComponent();
}

private string header;
public string Header
{
get { return header; }
set
{
header = value;
OnPropertyChanged("Header");
}
}

protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

public event PropertyChangedEventHandler PropertyChanged;
}

在 UserContol xaml 中:

Label Name="lbHeader" Grid.Column="0" Content="{Binding Path=Header}"

如果我设置值:AA2P.Header = "SomeHeeaderText";label.Caption 将不会改变。我该如何解决这个问题?

在 Windows xaml 中:

uc:SomeClass x:Name="AA2P" 

如果我直接给标签 (lbHeader.Content = header;) 而不是 OnPropertyChanged("Header"); 赋值它的工作但是,为什么它不使用 OnPropertyChanged 吗?


我需要将 DataContext 用于其他用途。我尝试使用依赖属性,但出了点问题。

public partial class tester : UserControl
{
public tester()
{
InitializeComponent();
}

public string Header
{
get { return (string)GetValue(MyDependencyProperty); }
set { SetValue(MyDependencyProperty, value); }
}
public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register("MyDependencyProperty", typeof(string), typeof(string));

}


<UserControl ... x:Name="mainControl">
<TextBlock Text="{Binding ElementName=mainControl, Path=MyDependencyProperty}"/>
</UserControl>


<Window ...>
<my:tester Header="SomeText" />
</Window>

它不起作用。我做错了什么?谢谢!

最佳答案

最简单的方法是仅使用对象的 DataContext。一种方法是直接在构造函数中这样做:

public SomeClass()
{
InitializeComponent();
DataContext = this;
}

设置 DataContext 将指定应从何处获取新数据。在名为 WPF Basic Data Binding FAQ 的文章中有一些很棒的提示和信息.阅读它以更好地理解 DataContex 的用途。它是 WPF/C# 中必不可少的组件。


由于问题的更新而更新。

据我了解,您应该将 DependencyProperty.Register 的第一个参数更改为您要绑定(bind)到的属性的名称,此处为 "Header" 以及类类型的第二个参数,此处为 SomeClass。那会给你留下:

public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register("Header", typeof(SomeClass), typeof(string));

但我很少使用依赖属性,所以我不确定这就是它,但它值得一试..

关于c# - WPF UserControl绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6547752/

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