ryrich
ryrich

Reputation: 2204

XAML/C# - Binding Property does not get called

Not sure why it does this...

I'm simplifying my problem for the sake of clarity. I have two variables that participate in data-binding. One variable is fetched fine, but the other one does not get fetched.

Example.xaml.cs:

public partial class Example : UserControl
{
    private string _name;
    private string _area;
    private AppClass _app;

    public Example(string name, AppClass app)
    {
        InitializeComponent();
        _name = name;
        _app = app;
        this.DataContext = this;
        InitializeData();
    }

    private void InitializeData()
    {
        if (_app != null)
        {
            _area = _app.GetArea();
        }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public string Area
    {
        get { return _area; }
        set { _area = value; }
    }
}

And my Example.xaml (just the lines of interest):

<TextBlock Grid.Row='0' Grid.Column ='0' Padding='5,0,0,0' Background='LightBlue' Text='Exchanger'/>
<TextBlock Grid.Row='0' Grid.Column ='1' Background='LightBlue' Text="{Binding Name}" TextAlignment='Center'/>

<TextBlock Grid.Row='2' Grid.Column ='0' Padding='5,0,0,0' Background='LightCyan' Text='Area'/>
<TextBlock Grid.Row='2' Grid.Column ='1' Background='LightCyan' Text="{Binding Area}" TextAlignment='Center'/>

Interestingly enough, Area gets called fine, but Name doesn't. I put a breakpoint on the getter of Name and Area and it breaks on Area but not Name. I'm perplexed...

Upvotes: 0

Views: 265

Answers (1)

Fede
Fede

Reputation: 44028

the Name property is defined in FrameworkElement. Change the property name to something else.

Also, The UI is not the right place to store your data. Instead of doing that, create a proper ViewModel to hold your data and make sure your usercontrol is bound to that ViewModel.

Upvotes: 1

Related Questions