0
votes

I try to bind a string array to a Datagrid column. I've got a int variable but I want to show a string value. So my idea is to bind a string array and use the int value as index.

public class TestStep : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged([CallerMemberName] string propName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }

    public int Mode { get; set; }

    public string[] ModeName { get; set; } = { "name1", "name2" };
}

So the XAML I use is:

<DataGrid ItemsSource="{Binding TestStep , UpdateSourceTrigger=PropertyChanged}" 
        <DataGrid.Columns>
            <DataGridTextColumn Header="Mode ID" Binding="{Binding Mode }" />
            <DataGridTextColumn Header="Mode ID Name" Binding="{Binding ModeName[0]}" />
            <DataGridTextColumn Header="Mode ID Name" Binding="{Binding ModeName[Mode]}" />
        </DataGrid.Columns>
    </DataGrid>

If I use Binding="{Binding ModeName[0]}" I get the correct value in the datagrid

If I use Binding="{Binding ModeName]Mode]} I get a Binding error:

System.Windows.Data Error: 40 : BindingExpression path error: '[]' property not found on 'object' ''String[]' (HashCode=62367561)'.
BindingExpression:Path=ModeName[{1}]; DataItem='TestStep' (HashCode=4862753); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

Why can't I resolute the variable Mode in the []Block?

Thanks

Best regards

1

1 Answers

1
votes

Why can't I resolve the variable Mode in the [] Block?

Binding path is not dynamic. ModeName[Mode] in xaml is interpreted as ModeName["Mode"] in c# (string indexer).

but you can create a special property using both ModeName and Mode, and bind to it:

public class TestStep : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged([CallerMemberName] string propName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }

    public int Mode { get; set; }

    public string[] ModeName { get; set; } = { "name1", "name2" };

    public string CurrentModeName
    { 
         get { return ModeName[Mode]; }
         set { ModeName[Mode] = value; }
    }
}
<DataGrid ItemsSource="{Binding TestStep}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Mode ID" Binding="{Binding Mode}" />
        <DataGridTextColumn Header="Mode ID Name" Binding="{Binding ModeName[0]}" />
        <DataGridTextColumn Header="Mode ID Name" Binding="{Binding CurrentModeName}" />
    </DataGrid.Columns>
</DataGrid>