【问题标题】:Two way binding to list of lists in WPF两种方式绑定到 WPF 中的列表列表
【发布时间】:2018-04-01 03:47:39
【问题描述】:

我正在尝试对包含双精度二维数组的 ListBox 进行双向绑定。为此,我使用自定义项目模板和值转换器,将我的二维数组转换为列表列表。 问题在于它只能以一种方式起作用。

我的列表框:

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

【问题讨论】:

  • 这不是二维数组,而是锯齿状数组。在 C# 中,二维数组被写入 T[,]。如果您要使用锯齿状数组,为什么不首先使用 List&lt;List&lt;T&gt;&gt; 并放弃转换?
  • “我知道只有当两个属性都是依赖属性时,双向绑定才有可能”。那是一种误解。虽然 Binding 的目标属性需要是依赖属性,但源属性不需要,即使它应该设置为 Binding。
  • 扩展克莱门斯点。您可以拥有一个实现 inotifypropertychanged 而不是依赖对象的对象的二维数组。 dp 绑定比 poco 上的属性快,如果你有很多这样的,那么 do 可能是一个更好的解决方案。
  • 你可以尝试让 dp 默认绑定双向。它是注册元数据选项之一。
  • “A dp binding is faster” 完全是无稽之谈,与问题的上下文无关。

标签: c# wpf xaml binding


【解决方案1】:

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

TwoWay 绑定适用于用户可以从 UI 更改值的 UI 元素。就像在文本框中一样。

也许你想在这个问题中得到类似的东西:How to assign controls in an ItemControl to the values in an ObservableCollection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2010-11-17
    • 2015-11-09
    • 2017-01-03
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多