我有一个自定义类:
class CustomClass
{
public string Test { get; set; }
CustomClass()
{
this.Test = "";
}
}
我在Application.Resources上声明这个自定义类:
<Application.Resources>
<local:CustomClass x:Key="myobj"/>
</Application.Resources>
此资源是网格的DataContext,TextBox绑定Test属性,如下所示:
<Grid DataContext="{DynamicResource myobj}">
<TextBox Text="{Binding Path=Test, Mode=TwoWay}"></TextBox>
</Grid>
突然在运行时,我更改了资源的值
this.Resources["myobj"] = new CustomClass() { Test = "12456" };
我希望TextBox上引用的值始终是当前“myobj”资源上的对象的值,并且我希望在TextBox的Text属性值更改时自动更改当前对象的值,因为其中,我使用了Mode = TwoWay,但它没有发生。
我使用了WPF Inspector,我看到资源值被更改时,绑定了一个新的已清除对象,而不是我创建的对象
我是WPF的新手,对不起我的英语和我的不知情;
此致
它可以实现ethicallogics发布的代码,谢谢!但是抱歉,如果我以前不清楚,何时绑定新资源
this.Resources["myobj"] = new instance;
它在声明此资源的同一窗口内调用时工作正常,不像我在UserControl中调用此行时,似乎UserControl不继承MainWindow资源,它是如何工作的?
答案 0 :(得分:0)
class CustomClass:INotifyPropertyChanged
{
private string _test;
public string Test
{
get
{
return _test;
}
set
{
_test = value;
Notify("Test");
}
}
CustomClass()
{
this.Test = "";
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void Notify(string propName)
{
if(PropertyChanged!=null)
PropertyChanged(this,new PropertyChangedEventArgs(propName);
}
}
使用此课程。我希望这会有所帮助。