我的代码同样令人震惊:
Xaml:
<UserControl.Resources>
<Bll:HandHeld x:Key="hh" >
</Bll:HandHeld>
</UserControl.Resources>用于绑定的另一个Xaml
<TextBox Name="txtHHName"
Text="{Binding Source={StaticResource hh}, Path=HandHeldName, Mode=TwoWay}" />在我的Csharp代码中:
HandHeld hh = this.FindResource("hh") as HandHeld;
hh.HandHeldName="testing";这段代码工作正常,因为我的类HandHeld实现了INotifyPropertyChanged,但是当我想要将一个属性应用于它自己的资源时,它不适用于绑定到它的textbox。
HandHeld hh = this.FindResource("hh") as HandHeld;
hh=new HandHeld(); //this line doest not affect. why ?或者这也不起作用。
this.resources["hh"]=new HandHeld();//this doesnt have any affect too.为什么?
发布于 2011-08-08 12:25:31
首先,
HandHeld hh = this.FindResource("hh") as HandHeld;
hh=new HandHeld(); &
this.resources["hh"]=new HandHeld();是不一样的。第一个实现使用在代码中声明的对象(这显然没有任何作用),而第二个实现使用HandHeld类的xaml对象。
第二个不起作用,因为当您设置对象时,没有任何东西可以通知更改。因此,您要么实现一个依赖属性,要么在其背后的当前代码中创建一个依赖属性。
public static readonly DependencyProperty HandHeldObjProperty =
DependencyProperty.Register("HandHeldObj", typeof(HandHeld), typeof(UserControl),new PropertyMetadata(null)); 将XAML中的上述依赖属性绑定到源。当你想设置这个值的时候,
SetValue(HandHeldObjProperty, new HandHeld());
编辑:
我认为你有一些地方,你特别想绑定你的对象。类似于检查对象(HandHeld对象)是否为空。
如果不是这样,那么您编写的代码应该可以工作。在初始化类之后,是否设置了依赖属性HandHeldName?我是说..。
this.resources["hh"]=new HandHeld();
hh.HandHeldName="testing";发布于 2011-08-08 15:07:41
好的,你可以这样做
this.Resources.Remove("hh");this.Resources.Add("hh",new HandHeld());//此行生效。
请核实并让我知道这是否有效。
https://stackoverflow.com/questions/6977494
复制相似问题