如何在绑定到画布的集合中找到具有特定值的项?

本文关键字:集合 绑定 | 更新日期: 2023-09-27 18:08:21

我在谷歌上搜索了一下,但没有得到任何真正的答案。可能是因为我的问题有点晦涩吧。是:

假设我有一个包含一堆模型的ObservableCollection<SomeModel>。然后将相应的视图添加到画布。在窗口的资源中指定这一点,然后将画布的ItemsSource绑定到ObservableCollection<SomeModel>。这很好。SomeModel被绑定到SomeView,这是一个UserControl。

现在,当这个视图获得焦点时,或者当我按下鼠标时,我想把它标记为"Selected"。不知何故,我想有一个属性的代码背后的窗口持有我的画布,在那里我总是可以得到选中的项目。

我一直在想有一个BindingList而不是ObservableCollection,当模型上的IsSelected属性发生变化时,一个方法将从列表中提取所选项目。但这似乎是一个性能杀手,因为我将被通知所有更改的项目。

我怎样才能做到这一点?

如何在绑定到画布的集合中找到具有特定值的项?

有多种方法可以解决这个问题。但可能最简单的方法是使用ListBox并绑定到它。ListBox,因为它有可绑定的ItemsSource和一个SelectedItem属性,其中包含当前被选中的项。如果你想在.cs文件后面的代码中做一些事情,当选择发生变化时,它也会调用SelectionChanged事件。

我建议在视图模型中保留ObservableCollection,以保持MVVM的真实性。

如果ListBox的样式或位置不适合您,则重写模板以更适合您的需求。

如果上面的方法不适合你,你可以查看一个行为,但最好保持简单。

这就是构建视图的方式。注意ItemsPanel属性被绑定到UserControl中定义的ItemsPanelTemplate。"资源"部分,该部分指定要放置项的画布。

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:local="clr-namespace:SilverlightApplication1"
x:Class="SilverlightApplication1.View1"
d:DesignWidth="640" d:DesignHeight="480">
<UserControl.Resources>
    <local:View1Model x:Key="View1ModelDataSource" />
    <ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
        <Canvas />
    </ItemsPanelTemplate>   
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource View1ModelDataSource}}">
    <ListBox Margin="80,85,183,54" ItemsPanel="{StaticResource ItemsPanelTemplate1}" ItemsSource="{Binding DataModelCollection}"/>
</Grid>

关于视图模型

public class View1Model
{
     private ObservableCollection<SomeModel> _DataModelCollection;
     public ObservableCollection<SomeModel> DataModelCollection
     {
        get { return this._DataModelCollection; }
        set { this._DataModelCollection = value; }
     }
 }

需要注意的是,Canvas本身并没有任何逻辑来允许用户在运行时移动控件。