MVVM binding properties and their properties

I have a view model that inherits from a base class that has the IsReadOnly property. In this view model, I have a Customer property and I bind the properties of the client object to the controls in my view.

However, I also want to be able to bind IsReadOnly to every control in my view.

<TextBox x:Name="FirstNameTextBox" Grid.Column="1" Margin="2,2,0,2" Grid.Row="2" TextWrapping="Wrap" HorizontalAlignment="Left" Width="200" 
                         Text="{Binding FirstName, Mode=TwoWay}" IsReadOnly="{Binding MyViewModel.IsReadOnly}"/>

How can I use both of these properties? here is my structure

public class MyViewModelBase {public bool IsReadonly {get; set;}}

public class MyViewModel {public client-client {get; set; }}

public class Customer {public string FamilyName {get; set; }}

Cheers for any help

+5
source share
2 answers

I assume your MyViewModel is inheriting from MyViewModelBase.

public class MyViewModelBase { public bool IsReadonly { get;set;} }

public class MyViewModel : MyViewModelBase  { public Customer Customer { get; set; } }

public class Customer { public string FamilyName { get; set; } }

I also assume that your DataContext view is an instance of MyViewModel, if you don't tell me :) your binding should look like this:

<TextBox x:Name="FirstNameTextBox" Grid.Column="1" Margin="2,2,0,2" Grid.Row="2"    TextWrapping="Wrap" HorizontalAlignment="Left" Width="200" 
         Text="{Binding Customer.FamilyName, Mode=TwoWay}" IsReadOnly="{Binding IsReadOnly}"/>

EDIT: if the DataContext of your TextBox is a Customer property, you should use a RelativeSource in your binding to IsReadOnly

0
source

Moving properties also works with Binding, so you can do the following to bind the base object to the IsReadonly property:

public class MyViewModel {
    public Customer Customer { get; set; }
}

public class Customer : Entity {
}

public class Entity {
    public bool IsReadonly { get;set;}
}

<Button IsEnabled="{Binding Customer.IsReadonly}" />

In the above example, I assume that your view is bound to an instance of "MyViewModel", and you probably already have a change in the properties in your properties.

+7
source

All Articles