C# 更改wpf静态资源的值

C# 更改wpf静态资源的值,c#,wpf,resourcedictionary,C#,Wpf,Resourcedictionary,如何在运行时更改WPF静态资源的值 我有以下资源 #.#mm #.#mm² #.#mm⁴ 一些文本块引用了哪一个 然后根据要绑定到控件的对象,我想更改格式。 我已在控件中设置属性,如下所示: public string LengthFormat { set { this.Resources["LengthFormat"] = value; } } public string AreaFormat { set { th

如何在运行时更改WPF静态资源的值

我有以下资源


#.#mm
#.#mm²
#.#mm⁴
一些文本块引用了哪一个


然后根据要绑定到控件的对象,我想更改格式。 我已在控件中设置属性,如下所示:

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观察更改。

我同意Claus的观点,因为静态资源不会被观察到,您的UI不会更改。我建议尝试将静态资源更改为动态资源

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


最明显的方法是切换到使用
DynamicSource
,这就是它的用途。

我收到一个错误,错误是:错误4不能在类型为“Binding”的“StringFormat”属性上设置“DynamicResourceExtension”。只能在DependencyObject的DependencyProperty上设置“DynamicResourceExtension”。哦,对了,这是有意义的。在这种情况下,您将无法应用我的解决方案。它只适用于从属财产