C# 数据绑定不适用于我的依赖项属性

C# 数据绑定不适用于我的依赖项属性,c#,wpf,xaml,data-binding,dependency-properties,C#,Wpf,Xaml,Data Binding,Dependency Properties,我正在用.NETFramework4和.NET开发一个WPF应用程序 我创建了一个仅包含DataGrid的自定义用户控件: 此控件定义依赖项属性SelectedItems: 最后,在视图中使用此自定义用户控件,定义如下: <Window x:Class="Project.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" x

我正在用.NETFramework4和.NET开发一个WPF应用程序 我创建了一个仅包含DataGrid的自定义用户控件:

此控件定义依赖项属性SelectedItems:

最后,在视图中使用此自定义用户控件,定义如下:

<Window x:Class="Project.Views.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="clr-namespace:Project.Views"
    Title="Project"
    Height="700" Width="1050"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}">

    <Window.Resources>
        <ResourceDictionary Source="Styles.xaml" />
    </Window.Resources>

    <Grid>
        <uc:CustomDataGrid DataContext="{Binding Items}"
            SelectedItems="{Binding SelectedItems}" />
    </Grid>
</Window>
使用相应的ViewModel:

我的问题是:当我从CustomDataGrid中选择一行或多行时,SelectedItems from MainViewModel不会更新。我想我没把什么东西接好,但我没找到什么


有什么想法吗?

将列表更改为ObservaleCollection,因为ObservaleCollection实现了INotifyCollectionChanged和INotifyPropertyChanged,而as列表没有这样做

您必须对SelectedItems属性进行双向绑定。要么在绑定表达式中显式执行此操作,如下所示:

<uc:CustomDataGrid ... SelectedItems="{Binding SelectedItems, Mode=TwoWay}"/>
<uc:CustomDataGrid DataContext="{StaticResource myViewModelInstance}"
    ItemsSource="{Binding Items}" SelectedItems="{Binding SelectedItems}"/>
需要显式设置SelectedItems绑定的绑定源对象,可能如下所示

SelectedItems="{Binding SelectedItems, Source={StaticResource myViewModelInstance}}"
除了SelectedItems属性之外,控件还应该具有可绑定的Items或ItemsSource,而不是这样做。然后,您可以简单地编写如下绑定:

<uc:CustomDataGrid ... SelectedItems="{Binding SelectedItems, Mode=TwoWay}"/>
<uc:CustomDataGrid DataContext="{StaticResource myViewModelInstance}"
    ItemsSource="{Binding Items}" SelectedItems="{Binding SelectedItems}"/>

我试过了,但没有成功,因为我没有用添加或删除之类的方法更新列表,我创建了一个新列表,因此引用不同。我同时添加了这两种方法,但效果不太好。我还仔细检查了输出窗口中的绑定错误,看起来还可以。所以一切似乎都很好。谢谢你,这就像一个魅力,代码看起来更好。你的回答现在被接受了:
<uc:CustomDataGrid DataContext="{Binding Items}"
    SelectedItems="{Binding SelectedItems}"/>
SelectedItems="{Binding SelectedItems, Source={StaticResource myViewModelInstance}}"
<uc:CustomDataGrid DataContext="{StaticResource myViewModelInstance}"
    ItemsSource="{Binding Items}" SelectedItems="{Binding SelectedItems}"/>