vrnithinkumar
vrnithinkumar

Reputation: 1363

How to dynamically bind a WPF Controls property with ViewModels different property?

For Example: We need to dynamically bind a RadioButton Value property with two different properties of ViewModel.

View Model

public class MyViewModel
{

//Property-1 to bind with RadioButton
        public bool Accepted
        {
            get;
            set;
        }

//Property-2 to bind with RadioButton
        public bool Enable
        {
            get;
            set;
        }

//Property to Identify which property should bind with radio button.
        public bool Mode
        {
            get;
            set;           
        }
}

Xaml

<RadioButton Value="{Binding Accepted, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Is it possible to dynamically bind Accepted or Enable property according to the Mode property?

Upvotes: 0

Views: 349

Answers (1)

poke
poke

Reputation: 387587

You cannot change the binding from the view model. You could however create a new property which you bind to that then delegates its value to the correct other value, e.g.:

public class ViewModel
{
    public bool Prop1 { get; set; }
    public bool Prop2 { get; set; }
    public bool Use2 { get; set; }

    public bool Prop
    {
        get { return Use2 ? Prop2 : Prop1; }
        set
        {
            if (Use2)
                Prop2 = value;
            else
                Prop1 = value;
        }
    }
}

Of course this example is missing the INotifyPropertyChanged implementation details.

Upvotes: 3

Related Questions