2012-01-14 155 views
6

如何在运行时更改WPF静态资源的值?更改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> 

其中一些的TextBlocks引用

<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; 
    } 
} 

然后结合之前,我设定的每个字符串。

然而,它不起作用,任何人都建议whynot?

干杯

回答

3

其实它工作得很好。但由于资源密钥未被观察到,因此UI未更新。

如果您想要可以更改的绑定,则不应使用静态资源。使用常规绑定代替INotifyPropertyChanged属性,允许UI观察更改。

0

我同意克劳斯作为静态资源将不会被观察你的用户界面不会改变。我会通过改变静态资源到动态资源

<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Breadth, StringFormat={DynamicResource ResourceKey=LengthFormat}}" /> 
+1

我收到一个错误消息:错误4无法在'绑定'类型的'StringFormat'属性上设置'DynamicResourceExtension'。 'DynamicResourceExtension'只能在DependencyObject的DependencyProperty上设置。 – 2012-01-14 13:52:41

+0

ohh对,有道理。在这种情况下,您将无法应用我的解决方案。它只适用于DependencyProperty – 2012-01-14 13:58:45

3

最显而易见的建议是尝试切换到使用DynamicResource这是它是什么。