我是 WPF 的初学者,在尝试将依赖属性绑定为 CollectionViewSource
的源时遇到问题。
用户控件公开 DependencyProperty
类型的 List
。它用于在 DataGrid
的帮助下将数据呈现在 CollectionViewSource
中(用于过滤、分组和排序操作)。
我的MainWindow XAML
:
<Window>
<local:CustomUserControl x:Name="CustomUCDataGrid" ListToDisplay="{Binding listFromDB}"/>
<Window>
我的MainWindow.cs
:
public partial class MainWindow : Window
{
public List<customType> listFromDB{get;set;}
public MainWindow{
listFromDB = GetListFromDB();
InitializeComponent();
this.DataContext = this;
}
}
CustomUserControl.xaml
看起来像:
<UserControl x:Name="ParentNode">
<DataGrid DataContext="{Binding ElementName=ParentNode}">
<StackPanel>
<DataGrid x:Name="DirectDataGrid" ItemSource="{Binding ListToDisplay}"/>
<DataGrid x:Name="DataGridWithCVS" ItemsSource="{Binding cvsList.View}"/>
</StackPanel>
</DataGrid>
</UserControl>
CustomUserControl.xaml.cs
看起来像:
public partial class CustomUserControl: UserControl
{
public List<customType> ListToDisplay{
get { return (List<customType>)GetValue(ListToDisplayProperty); }
set { SetValue(ListToDisplayProperty, value); }
}
public static readonly DependencyProperty ListToDisplayProperty=
DependencyProperty.Register("ListToDisplay", typeof(List<customType>),
typeof(CustomUserControl));
public CollectionViewSource cvsList { get; set; }
public CustomUserControl{
InitializeComponent();
cvsList = new CollectionViewSource();
cvsList.Source = ListToDisplay;
DataGridWithCVS.ItemsSource = CollectionViewSource.GetDefaultView(cvsList);
}
}
此处名称为 "DirectDataGrid" 的 DataGrid 没有问题可以显示从 MainWindow 提供给它的数据,但是 DataGrid 具有name "DataGridWithCVS" 不显示任何数据。调试时找不到任何错误。
我已经尝试过的事情:
<UserControl x:Name="ParentNode"> <DataGrid DataContext="{Binding ElementName=ParentNode}">...
)。答案 0 :(得分:1)
这只是某种疯狂:)
留下代码。
在您的情况下,除了声明 DependecyProperty 之外,应该没有任何内容。
<UserControl x:Name="ParentNode">
<UserControl.Resources>
<CollectionViewSource x:Key="cvsList"
Source="{Binding ListToDisplay, ElementName=ParentNode}"/>
</UserControl.Resources>
<StackPanel>
<DataGrid x:Name="DirectDataGrid" ItemsSource="{Binding ListToDisplay, ElementName=ParentNode}"/>
<DataGrid x:Name="DataGridWithCVS" ItemsSource="{Binding Mode=OneWay, Source={StaticResource cvsList}}"/>
</StackPanel>
</UserControl>