我已经构建了一个自定义控件,可以在其他控件中封装数据网格。我遇到的问题是当我更新绑定到datagrid.itemsouce的集合时,dependencyProperty永远不会被触发。我有一个回调事件,需要在ItemSource属性更改时调用
自定义控件中的我的DataGrid:
<DataGrid x:Name="Grid"
AutoGenerateColumns="True"
IsReadOnly="True"
SelectionMode="Single"
SelectedItem="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Selected, Mode=TwoWay}"
ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchResultSource, Mode=TwoWay}" />
我的ItemSource依赖代码:
public static readonly DependencyProperty SearchResultSourceProperty =
DependencyProperty.Register("SearchResultSource", typeof(IEnumerable), typeof(dg), new PropertyMetadata(null, new PropertyChangedCallback(SearchResultSourcePropertyChanged)));
ublic IEnumerable SearchResultSource
{
get
{
return (IEnumerable)GetValue(SearchResultSourceProperty);
}
set
{
SetValue(SearchResultSourceProperty, value);
}
}
private static void SearchResultSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var value = e.NewValue as IEnumerable;
if (value != null)
{
int count = Enumerable.Count<object>(value.Cast<object>());
if (count > 0)
{
o.SetValue(IsOpenProperty, true);
}
else
{
o.SetValue(IsOpenProperty, false);
}
我的观点:
<control:dg x:Name="gg"
Search="lookupControl_Search"
SearchButtonContent="Find Member"
SearchResultSource="{Binding People, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Selected="{Binding SelectedItem, Mode=TwoWay}"
SelectedChanged="lookupControl_SelectionChanged"/>
“lookupControl_Search”连接到与button.click事件关联的路由事件。现在被解雇了,我可以看到更新的ObervableCollection,但SearchResultSource属性永远不会被触发。我很困惑,因为当ObservableCollection首次初始化时会被触发。
我试图刷新CustomTemplate中DataGrid中的项目,并且我还尝试在routedEvent for button.Click之后设置绑定到网格:
var grid = this.GetTemplateChild("Grid") as DataGrid;
Binding b = new Binding() { Mode = BindingMode.TwoWay, Source = SearchResultSource, Path= new PropertyPath(SearchResultSourceProperty) };
BindingOperations.SetBinding(grid, DataGrid.ItemsSourceProperty, b);
我对WPF很新,所以我知道我错过了什么,但经过几个小时的研究,我还没有找到解决方案。有什么想法吗?
非常感谢!