C#WPF绑定未更新
我正在尝试创建一个自定义控件,可以在其中绑定一个属性,就像TextBox有Text属性和大量其他控件一样 问题是,当我从MainWindow绑定属性时,该属性不会更新 我浏览了好几页,尝试了很多选择,但都没有成功。最后,我终于找到了一个可行的解决方案,其中包括更改控件的DataContext:C#WPF绑定未更新,c#,wpf,xaml,dependency-properties,C#,Wpf,Xaml,Dependency Properties,我正在尝试创建一个自定义控件,可以在其中绑定一个属性,就像TextBox有Text属性和大量其他控件一样 问题是,当我从MainWindow绑定属性时,该属性不会更新 我浏览了好几页,尝试了很多选择,但都没有成功。最后,我终于找到了一个可行的解决方案,其中包括更改控件的DataContext: ((FrameworkElement) this.Content).DataContext = this; 在我使用this.DataContext=this之前,控件内的所有值都已更新,但其他值均未更
((FrameworkElement) this.Content).DataContext = this;
在我使用this.DataContext=this
之前,控件内的所有值都已更新,但其他值均未更新
问题:
(对我来说)找到的解决方案看起来像是一些丑陋的变通办法
//XAML
//什么地方有房产
公共字符串SomeProperty{get;set;}
示例控件
//XAML
打印文本!
//相关代码
公共静态只读从属属性MyValueProperty=
DependencyProperty.RegisterAttached(“MyValue”、typeof(字符串)、typeof(ExampleControl)、new FrameworkPropertyMetadata
{
BindsTwoWayByDefault=true,
DefaultUpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged
});
公共字符串MyValue
{
获取{返回GetValue(MyValueProperty)作为字符串;}
set{SetValue(MyValueProperty,value);}
}
//在构造函数中,使其工作。
((FrameworkElement)this.Content).DataContext=this;
谢谢 由于您提供的信息太少,代码会很好,我有一些注释要给您
- 在源上使用INotifyPropertyChanged接口进行绑定。-您必须提高PropertyChanged才能使绑定工作
- 创建新的CustomControl时,请确保控件的属性是DependendyProperties
- 在源上使用INotifyPropertyChanged接口进行绑定。-您必须提高PropertyChanged才能使绑定工作
- 创建新的CustomControl时,请确保控件的属性是DependendyProperties
// XAML
<local:ExampleControl MyValue="{Binding SomeProperty}"></local:ExampleControl>
// Where SomeProperty
public string SomeProperty { get; set; }
// XAML
<TextBox Grid.Column="0" Text="{Binding MyValue}"></TextBox>
<Button Grid.Column="1" Click="Button_Click">Print Text!</Button>
// Relevant code
public static readonly DependencyProperty MyValueProperty =
DependencyProperty.RegisterAttached("MyValue", typeof(string), typeof(ExampleControl), new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
});
public string MyValue
{
get { return GetValue(MyValueProperty) as string; }
set { SetValue(MyValueProperty, value); }
}
// In constructor, to make it work.
((FrameworkElement) this.Content).DataContext = this;