CodeMonkey
CodeMonkey

Reputation: 12424

WPF binding to an already bound property

What can I do if I want to bind to some property which is already bound to something else?

In my case, I got a window which has a TextBox. The Text property of this TextBox is data bound to a combo box to it's selectedItem. My Window class got a public string property which I want to update with whatever value is in the TextBox so I wanted to data bind with the Text property but as I said, it's already bound.

How can I update my property with the text in TextBox? Must it use a routed event of TextChanged or can I do it via Xaml?

Also specifically with properties you define them yourself in your window.cs ... how can you bind them to the TextBox.Text? I tried doing it with the <Window> declaration, meaning <Window MyProperty={Binding ...} /> but the property is not recognized there. Why and how do I do it?

Upvotes: 1

Views: 647

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292425

You could solve this easily using the MVVM pattern.

ViewModel:

public class ChooseCategoryViewModel : ViewModelBase
{
    private string[] _categories =
        { "Fruit", "Meat", "Vegetable", "Cereal" };

    public string[] Categories
    {
        get { return _categories; }
    }

    private string _selectedCategory;
    public string SelectedCategory
    {
        get { return _selectedCategory; }
        set
        {
            _selectedCategory = value;
            OnPropertyChanged("SelectedCategory");
                            if (value != null && CategoryName != value)
                                CategoryName = value;
        }
    }

    private string _categoryName;
    public string CategoryName
    {
        get { return _categoryName; }
        set
        {
            _categoryName = value;
            OnPropertyChanged("CategoryName");
            if (Categories.Contains(value))
            {
                SelectedCategory = value;
            }
            else
            {
                SelectedCategory = null;
            }
        }
    }
}

XAML:

<ComboBox ItemsSource="{Binding Categories}"
          SelectedItem="{Binding SelectedCategory}" /> 
<TextBox Text="{Binding CategoryName}" />

Upvotes: 2

Related Questions