Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding with Path and Source in code in WPF

Tags:

c#

binding

wpf

xaml

I have this XAML:

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

I'm using this to bind string and be able to change them at runtime:

WPF Runtime Localization

Now my problem is I need to do the same binding in code, but I don't know how to specify the Source in the Binding. I know I can give the Path or the property name in the constructor of the class, but I'm unsure on how to access the Source property or even to define it to the StaticResource.

like image 668
Mokmeuh Avatar asked Mar 17 '26 01:03

Mokmeuh


1 Answers

Here is an example of Binding in code for Label.Content property, what I tested:

// 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);

In your case it will be something like this:

var binding = new Binding();
binding.Path = new PropertyPath("celsiusBtn");
binding.Source = (ObjectDataProvider)App.Current.FindResource("Resources");

celsiusBtn.SetBinding(MenuItem.HeaderProperty, binding);
like image 52
Anatoliy Nikolaev Avatar answered Mar 19 '26 15:03

Anatoliy Nikolaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!