【问题标题】:Get the AllowDrop propert of a Model in a ViewModel in WPF Treeview在 WPF Treeview 中的 ViewModel 中获取模型的 AllowDrop 属性
【发布时间】:2017-12-05 21:26:10
【问题描述】:

我有一个具有 AllowDrop 属性的模型类 ViewItem。我的视图模型 ViewModel 是 ViewItem 的可观察集合。

ViewItem 属性

    public bool AllowDrop
    {
        get
        {
            return _allowDrop;
        }
    }

我有一个 ViewTree,它的数据源绑定到 ViewModel 的一个实例 MyItems。

我希望能够访问将 ViewTreeItems AllowDrop 属性绑定到底层模型,但是我不知道访问它的正确方法。

我的 TreeView XAML 看起来像这样

        <TreeView x:Name="ViewsTree"
                  AllowDragDrop="True"
                  DragOver="ViewsTree_DragOver"
                  ItemsSource="{Binding MyItems}" 
                  ItemTemplate="{StaticResource ViewTemplate}"
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="AllowDrop" Value="{Binding}"/>
        </Style>
    </TreeView> 

我不知道如何访问 MyView 集合中的 ViewItem 以绑定到 AllowDrop 属性。

【问题讨论】:

  • 您的问题太模糊,无法回答。它不包括minimal reproducible example,但更关键的是,根本不清楚数据中找到的多个值为何以及如何映射到视图中的一个单个值。如果不是所有的视图项AllowDrop 属性都具有相同的值,您期望会发生什么。无论您期望什么,为什么您认为这是一个合适的选择?在我看来,将属性放在容器视图模型对象中更有意义,该对象引用项目集合和单个属性。

标签: c# wpf xaml mvvm treeview


【解决方案1】:

这是一个最简单的例子。

XAML:

<Grid>
    <Grid.Resources>
        <ResourceDictionary>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="AllowDrop" Value="{Binding AllowDrop}"/>
            </Style>
        </ResourceDictionary>
    </Grid.Resources>

    <TreeView ItemsSource="{Binding MyItems}">
        <TreeView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Id}"/>
                    <TextBlock Margin="5,0" Text="{Binding AllowDrop}"/>
                </StackPanel>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>

后面的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new ViewModel();
    }
}

public class ViewModel
{
    public ViewModel()
    {
        MyItems = new List<ViewItem>();
        for (int i = 0; i < 10; i++)
            MyItems.Add(new ViewItem { Id = i, AllowDrop = i % 2 == 0 });
    }

    public List<ViewItem> MyItems { get; set; }
}

public class ViewItem
{
    public int Id { get; set; }
    public bool AllowDrop { get; set; }
}

尝试在 TreeListView 上拖动某些内容将仅适用于具有偶数 Id 的项目。

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 2011-04-29
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多