[英]Binding the ItemsSource of a ListView to the property of an already bound property
[英]WPF binding to an already bound property
如果我想綁定到已經綁定到其他東西的某個屬性,該怎么辦?
就我而言,我有一個帶有TextBox的窗口。 此TextBox的Text屬性是綁定到其selectedItem組合框的數據。 我的Window類有一個公共字符串屬性,我想用TextBox中的任何值更新它,因此我想用Text屬性進行數據綁定,但是正如我所說的,它已經綁定了。
如何使用TextBox中的文本更新屬性? 它必須使用TextChanged的路由事件,還是可以通過Xaml完成?
同樣特別是使用屬性,您可以在window.cs中自行定義它們……如何將它們綁定到TextBox.Text? 我嘗試使用<Window>
聲明來執行此操作,這意味着<Window MyProperty={Binding ...} />
但是在那里無法識別該屬性。 為什么以及如何做?
您可以使用MVVM模式輕松解決此問題。
視圖模型:
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}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.