Guillermo Mestre
Guillermo Mestre

Reputation: 490

How to make a basic binding work

I'm sure that this (kind of) question is already duplicate so please don't be hard on me ^_^ I'm hitting in the dark with this one and having trouble understanding the whole picture, so I'm not sure what to look for.

A Card is a custom immutable class with lots of properties (some of them are other classes too) but to simplify let's say that a Card is this:

public class Card
{
    public string Name { get; private set; }
    public int Power { get; private set; }

    private Card() { }
    public Card(string name, int power)
    {
        Name = name;
        Power = power;
    }
}

CardView is a UserControl that represents a Card on the UI. It has a Card attached to it.

XAML:

<UserControl ... yadayada ...>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0">Name: </TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding Name}" />
    <TextBlock Grid.Column="0" Grid.Row="1">Power: </TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Power}" />
</Grid>
</UserControl>

Code behind:

public partial class CardView : UserControl
    {
        public static readonly DependencyProperty CardProperty = DependencyProperty.Register("Card", typeof(Card), typeof(CardView));

        private Card _card;
        public CardView()
        {
            InitializeComponent();
            _card = new Card("Chuck", 999);
            this.DataContext = _card;
        }
    }

It shows the correct values when created, but I'm missing the last step to allow me to swap the Card at run time.

Edit: In case I didn't explained well, this is what I want to be able to do:

Let's say that I add this method to CardView:

public void SetCard(Card card)
{
    _card = card;
}

How can I make the bindings update?

Upvotes: 1

Views: 55

Answers (1)

Laith
Laith

Reputation: 6091

You have to update the DataContext as well:

public void SetCard(Card card)
{
    _card = card;
    this.DataContext = _card;
}

Upvotes: 1

Related Questions