我有这个XAML:
<MenuItem Name="celsiusBtn"
Header="{Binding Path=celsiusBtn, Source={StaticResource Resources}}"
IsChecked="True"
Click="celsiusBtn_Click" />
我正在使用它来绑定字符串,并且能够在运行时更改它们:
现在我的问题是我需要在代码中执行相同的绑定,但我不知道如何在Source
中指定Binding
。我知道我可以在类的构造函数中提供Path
或属性名称,但我不确定如何访问Source属性甚至将其定义为StaticResource
。
答案 0 :(得分:2)
以下是Binding
属性代码中Label.Content
的示例,我测试的是:
// analogue of this line:
// {Binding Path=LabelCultureName, Source={StaticResource Resources}}
var binding = new Binding();
binding.Path = new PropertyPath("LabelCultureName");
binding.Source = (ObjectDataProvider)App.Current.FindResource("Resources");
TestLabel.SetBinding(Label.ContentProperty, binding);
在你的情况下,它将是这样的:
var binding = new Binding();
binding.Path = new PropertyPath("celsiusBtn");
binding.Source = (ObjectDataProvider)App.Current.FindResource("Resources");
celsiusBtn.SetBinding(MenuItem.HeaderProperty, binding);