我有 ListView
,同一列中有不同的单元格(通过使用 DataTemplateSelector
实现)。这是一个非常简单的例子:
<ListView ItemsSource="{Binding Items}">
<ListView.Resources>
<l:ResultsSelector x:Key="result1">
<l:ResultsSelector.TemplateResult>
<DataTemplate>
<TextBlock Text="{Binding Result1}"/> <!-- how to make this dynamic? -->
</DataTemplate>
</l:ResultsSelector.TemplateResult>
...
</l:ResultsSelector>
...
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn Header="Result1" CellTemplateSelector="{StaticResource result1}"/>
<!-- would be nice to use same selector for all columns -->
<GridViewColumn Header="Result2" CellTemplateSelector="{StaticResource result2}"/>
<GridViewColumn Header="Result3" CellTemplateSelector="{StaticResource result3}"/>
...
</GridView>
</ListView.View>
</ListView>
View 模型:
private ObservableCollection<Item> _items;
public ObservableCollection<Item> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged();
}
}
public class Item: NotifyPropertyChangedBase
{
public string Result1 {get; set;}
public string Result2 {get; set;}
public string Result3 {get; set;}
...
}
问题:ResultSelector
对于所有结果列(也有其他列)都是相同的,唯一的区别是绑定(bind)属性的名称:对于列“Result1”,它是Result1
、IsResult1
等,对于“Result2” - Result2
、IsResult2
等
目标:我只想定义一次选择器(正如我之前所说,这是非常简化的版本,所以复制/粘贴“result1”选择器定义 N
times 是一个非常糟糕的选择,特别是如果我以后必须更改某些东西)并以某种方式将它用于所有列。
问题:有没有办法组织动态绑定(bind)。在动态下,我的意思是根据列动态解析属性名称。
转换器? 用户控件
?想法?
最佳答案
想要什么
public String Name
{
get { return name; }
set { name = value; OnPropertyChanged("name"); }
}
和
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
有可能吗?这样您至少可以生成字符串并将其作为参数添加到 OnPropertyChanged。
关于c# - 动态绑定(bind)——根据列解析属性名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699556/