以下XAML代码可以正常运行:
<TextBlock Text="{DynamicResource myresourceitem}"/>
在myresourceitem&#39;的代码更改背后。更改文本块的文本,一切都很好。
但是,当我尝试在后面的代码中创建此文本块时,文本块会显示&#39; myresourceitem&#39;的文本,但在更改了myresourceitem&#39;之后不会更新:
Dim tb As New TextBlock
......
......
Dim bnd As New Binding
bnd.Source = Application.Current.FindResource("myresourceitem")
tb.SetBinding(TextBlock.TextProperty, bnd)
&#39; myresourceitem&#39;是Application.Current.Resources的资源。 我做错了什么?为什么这种绑定不能正常工作? 我是否必须将bnd.Path设置为某个值?
答案 0 :(得分:1)
您的XAML和您的代码不根本不做同样的事情。您的XAML将TextBlock.Text
属性设置为DynamicResource
myresourceitem
,不 Binding
。另一方面,您的代码似乎是尝试使用Binding
资源创建myresourceitem
Binding Source
。
然而,这应该是双向的。因此,我只能假设您没有正确访问您的资源...您是否在此行收到错误,说 myresourceitem
资源未找到?:
bnd.Source = Application.Current.FindResource("myresourceitem")
在将Resource
添加到Loaded
事件处理程序中之前,您也可能尝试访问string
...您是否尝试在构造函数中访问它?我使用简单的myresourceitem
作为DynamicResource
值测试了您的代码,它的工作正常。
更新&gt;&gt;&gt;
要以编程方式设置// To change the value:
Application.Current.Resources["myresourceitem"] = "Some new value";
// To set the value
tb.SetResourceReference(TextBlock.TextProperty, "myresourceitem");
,您需要使用FrameworkElement.SetResourceReference
method:
DynamicResource
请注意,您可以在设置{{1}}后轻松更改上述值...因为它是动态的。