【发布时间】:2022-01-12 20:07:54
【问题描述】:
我正在尝试创建一个自定义用户控件,其中包含一个 ListView,其中包含如下所示的数据模板:
<ComboBox ItemsSource="{Binding ItemsSource, ElementName=root}"
SelectedItem="{Binding SelectedItem, ElementName=root, Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- This is what I tried:
Working but not what I want <TextBox Text="{Binding Name}"/>
Returns the List only the word "FallBack" <TextBox Text="{Binding ItemText, ElementName=root}" />
Returns the LIst empty <TextBox Text="{Binding ItemText}" />
-->
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
在后面的代码中,我为这种情况创建了必要的依赖属性(所以我假设)唯一相关的是关于项目文本,它看起来像这样:
#region ItemText
public string ItemText
{
get { return (string)GetValue(ItemTextProperty); }
set { SetValue(ItemTextProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemTextProperty =
DependencyProperty.Register("ItemText", typeof(string), typeof(CardComboBox), new PropertyMetadata("FallBack"));
#endregion
我想做的是像这样添加用户控件
<local:CardComboBox ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson}" ItemText="{Binding Name}" IsEnabled="True" />
选项一:
<TextBox Text="{Binding Name}"/>
工作正常,因为类 Person 的 PropertyName 是 Name,但我显然不想硬编码它。我想将它绑定到我喜欢的任何属性。
选项 2:
<TextBox Text="{Binding ItemText, ElementName=root}" />
给我 7 个项目的列表(根据列表),但由于 DependencyPropertyMetadata 仅显示单词“Fallback”。
选项 3:
<TextBox Text="{Binding ItemText}" />
给我列表,但根本没有文字。
我也尝试使用 relativeSource,但结果相似。
#region Person
Person _selectedPerson;
public Person SelectedPerson
{
get => _selectedPerson;
set
{
if (value != _selectedPerson)
{
_selectedPerson = value;
OnPropertyChanged("SelectedPerson");
}
}
}
ObservableCollection<Person> _persons;
public ObservableCollection<Person> Persons
{
get => _persons;
set
{
if (value != _persons)
{
_persons = value;
OnPropertyChanged("Persons");
}
}
}
public void populatePersons()
{
Persons = new ObservableCollection<Person>();
Persons.Add(new Person("Carl"));
Persons.Add(new Person("Max"));
Persons.Add(new Person("May"));
Persons.Add(new Person("Jen"));
Persons.Add(new Person("Charly"));
Persons.Add(new Person("Nora"));
Persons.Add(new Person("Yvonne"));
}
#endregion
我已经添加了我要绑定的列表。方法 Populate Persons 在 ViewModel 的构造函数中被调用。
【问题讨论】:
标签: wpf listview combobox binding user-controls