Dynamic binding - resolving property name based on

2019-06-26 06:15发布

I have ListView with different cells in same column (achieved by using DataTemplateSelector). Here is very simplified example:

<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-model:

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;}
    ...
}

Problem: ResultSelector is the same for all result columns (there are also other columns), the only difference is names of bound properties: for column "Result1" it's Result1, IsResult1, etc., for "Result2" - Result2, IsResult2, etc.

Aim: I'd like to define selector just once (as I said earlier, this is very simplified version, so copy/paste "result1" selector definition N times is pretty bad option, especially if I have to change something later) and use it for all columns somehow.

Question: is there a way to organize dynamic binding. Under dynamic I mean dynamically resolved property name depending on column.

Converter? UserControl? Ideas?

1条回答
等我变得足够好
2楼-- · 2019-06-26 06:56

Would something like

public String Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("name"); }
    }

and

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }

be a possibility? This way you could at least generate the string and add this as a parameter to the OnPropertyChanged.

查看更多
登录 后发表回答