双向绑定到WPF中的列表列表

时间:2018-03-31 08:20:23

标签: c# wpf xaml binding

我正在尝试对包含2D数组double的ListBox进行双向绑定。为此我使用自定义项模板和值转换器将我的2D数组转换为列表列表。 问题是只能以一种方式运作。

我的列表框:

<ListBox ItemTemplate="{StaticResource double2dArray}" 
         ItemsSource="{Binding CoEmergenceProbability,
                       Converter={StaticResource double2DArrayConverter},
                       Mode=TwoWay,
                       RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}},
                       UpdateSourceTrigger=PropertyChanged
                      }"
 />

转换器:

public class Double2DArrayToListConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return new List<List<double>>();
        }
        double[][] values = (double[][])value;
        List<List<double>> res = new List<List<double>>(values.Length);
        for (int i = 0; i < values.Length; i++)
        {
            res.Add(values[i].ToList());
        }
        return res;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        List<List<double>> values = (List<List<double>>)value;
        double[][] res = new double[values.Count][];
        for (int i = 0; i < values.Count; i++)
        {
            res[i] = values[i].ToArray();
        }
        return res;
    }
}

自定义模板:

<DataTemplate x:Key="editableDouble">
        <TextBox Text="{Binding Path=.}" Width="70" Height="25" Margin="4" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"></TextBox>
</DataTemplate>
<DataTemplate x:Key="double2dArray">
    <ItemsControl ItemsSource="{Binding}" ItemTemplate="{StaticResource editableDouble}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"></StackPanel>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</DataTemplate>

1 个答案:

答案 0 :(得分:0)

ItemSource上的TwoWay绑定在逻辑上是无用的......如果要更改项目,则必须更改模型并自动更新视图。你永远不会有相反的方式!

TwoWay Bindings用于UI元素,其中用户可以从UI更改值。就像在TextBox中一样。

也许你想得到这样的问题:How to assign controls in an ItemControl to the values in an ObservableCollection