[英]Change the value of a wpf static resource
如何在運行時更改 WPF 靜態資源的值?
我有以下資源
<UserControl.Resources>
<sys:String x:Key="LengthFormat">#.# mm</sys:String>
<sys:String x:Key="AreaFormat">#.# mm²</sys:String>
<sys:String x:Key="InertiaFormat">#.# mm⁴</sys:String>
</UserControl.Resources>
其中一些文本塊參考
<TextBlock Grid.Row="2" Grid.Column="1"
Text="{Binding Path=Breadth, StringFormat={StaticResource ResourceKey=LengthFormat}}" />
然后根據要綁定到控件的對象,我想更改格式。 我在控件中設置了如下屬性:
public string LengthFormat
{
set
{
this.Resources["LengthFormat"] = value;
}
}
public string AreaFormat
{
set
{
this.Resources["AreaFormat"] = value;
}
}
public string InertiaFormat
{
set
{
this.Resources["InertiaFormat"] = value;
}
}
然后在綁定之前我設置了每個字符串。
但是它不起作用,有人建議為什么不?
干杯
實際上它工作得很好。 但是 UI 沒有更新,因為沒有觀察到資源鍵。
如果您想要可以更改的綁定,則不應使用靜態資源。 改用常規綁定,在屬性上使用INotifyPropertyChanged
,允許 UI 觀察更改。
最明顯的方法是切換到使用DynamicResource
這就是它的用途。
我同意 Claus 的觀點,因為不會觀察到靜態資源,您的 UI 不會改變。 我建議嘗試將靜態資源更改為動態資源
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Breadth, StringFormat={DynamicResource ResourceKey=LengthFormat}}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.