Andy
Andy

Reputation: 820

Binding Control IsChecked in the code behind

I'm generating some elements of my user interface on the fly to prevent duplication of the same code across my windows as they are very similar on the design. One control that I'm generating is a toggle switch which is currently binding like this in xaml:

IsChecked="{Binding DebugEnabled, Source={StaticResource NotifyFields}}

How do I go about moving this into the c# code behind for when this control is generated?

var tsGeneratedSwitch = new ToggleSwitch
{
    Header = "View Information",
    OffLabel = "No",
    OnLabel = "Yes",
    IsChecked = False,
};
tsGeneratedSwitch.Checked += SwitchChanged;
tsGeneratedSwitch.Unchecked += SwitchChanged;

Many thanks

Upvotes: 0

Views: 388

Answers (1)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4908

var myBinding = new Binding
{
    Source = NotifyFields,
    Path = new PropertyPath("DebugEnabled"),
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};

BindingOperations.SetBinding(tsGeneratedSwitch, CheckBox.IsCheckedProperty, myBinding);

Upvotes: 1

Related Questions