在WPF中的代码中使用Path和Source进行绑定

时间:2014-03-02 02:26:52

标签: c# wpf xaml binding

我有这个XAML:

<MenuItem Name="celsiusBtn"
          Header="{Binding Path=celsiusBtn, Source={StaticResource Resources}}" 
          IsChecked="True"
          Click="celsiusBtn_Click" />

我正在使用它来绑定字符串,并且能够在运行时更改它们:

WPF Runtime Localization

现在我的问题是我需要在代码中执行相同的绑定,但我不知道如何在Source中指定Binding。我知道我可以在类的构造函数中提供Path或属性名称,但我不确定如何访问Source属性甚至将其定义为StaticResource

1 个答案:

答案 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);