我的应用程序中有一个自定义数据网格,当它的源为空时,它应显示一条消息“无结果”,当源不为空时,它应显示源数据,不应显示任何消息。
我的自定义数据网格是:
namespace GenericControls
{
[TemplatePart(Name = "EmptyDataGridTextBlock", Type = typeof(TextBlock))]
public class CustomDataGrid : DataGrid
{
private TextBlock _txtEmptyDataGrid = null;
public static readonly DependencyProperty IsEmptyDataGridProperty = DependencyProperty.Register("IsEmptyDataGrid", typeof(bool), typeof(CustomDataGrid), null);
public static readonly DependencyProperty EmptyDataGridTextProperty = DependencyProperty.Register("EmptyDataGridText", typeof(string), typeof(CustomDataGrid), null);
public CustomDataGrid()
{
IsEmptyDataGrid = true;
}
public bool IsEmptyDataGrid
{
get
{
return (bool)base.GetValue(IsEmptyDataGridProperty);
}
set
{
base.SetValue(IsEmptyDataGridProperty, value);
if(_txtEmptyDataGrid != null)
{
_txtEmptyDataGrid.Visibility = IsEmptyDataGrid ? Visibility.Visible : Visibility.Collapsed;
}
}
}
public string EmptyDataGridText
{
get
{
if (_txtEmptyDataGrid != null)
{
return _txtEmptyDataGrid.Text;
}
return (string)base.GetValue(EmptyDataGridTextProperty);
}
set
{
if (_txtEmptyDataGrid != null)
{
_txtEmptyDataGrid.Text = value;
}
base.SetValue(EmptyDataGridTextProperty, value);
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_txtEmptyDataGrid = GetTemplateChild("EmptyDataGridTextBlock") as TextBlock;
if (_txtEmptyDataGrid != null)
{
_txtEmptyDataGrid.Text = EmptyDataGridText;
_txtEmptyDataGrid.Visibility = IsEmptyDataGrid ? Visibility.Visible : Visibility.Collapsed;
}
}
}
}
我的XAML如下:my:CustomDataGrid Height =“180”Name =“dgChildren”SelectedItem =“{Binding SelectedChild,Mode = TwoWay}”ItemsSource =“{Binding Childrens}” IsEmptyDataGrid =“{Binding IsEmptyDataGrid}“>
在我的ViewModel中,我有属性IsEmptyDataGrid:
public bool IsEmptyDataGrid
{
get
{
return _isEmptyDataGrid;
}
set
{
_isEmptyDataGrid = value;
RaisePropertyChanged("IsEmptyDataGrid");
}
}
我的问题是,即使我的视图模型中的RaisePropertyChanged("IsEmptyDataGrid")
被命中,它也不会进入自定义数据网格中的IsEmptyDataGrid
属性,并且空信息会随着数据一起显示在源。
我做错了什么?
提前谢谢你, Kruvi
答案 0 :(得分:1)
在这种情况下,并不总是调用DependencyProperty的setter。改为使用回调函数:
public static readonly DependencyProperty IsEmptyDataGridProperty = DependencyProperty.Register("IsEmptyDataGrid", typeof(bool), typeof(CustomDataGrid), new UIPropertyMetaData(false,Callback));
private static void Callback(DependecyObject d, DependencyPropertyChangedEventArgs e)
{
CustomDatagrid cdt = d as CustomDatagrid;
if(cdt._txtEmptyDataGrid != null)
{
cdt._txtEmptyDataGrid.Visibility = cdt.IsEmptyDataGrid ? Visibility.Visible : Visibility.Collapsed;
}
}