[英]Property Binding to Dependency property in Custom control not working
我用DependencyProperty创建了一个名为“ ItemsPerPage”的自定义控件。 我已经在窗口中使用了该自定义控件。 现在,如果我直接将值分配给ItemsPerPage属性,那么它将起作用,但是如果我将其与window中定义的属性绑定,则它将无法起作用。
海关管制声明。
public class SmartDataGrid : DataGrid
{
public SmartDataGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SmartDataGrid), new FrameworkPropertyMetadata(typeof(SmartDataGrid)));
}
public static readonly DependencyProperty ItemsPerPageProperty =
DependencyProperty.Register("ItemsPerPage", typeof(Int32),
typeof(SmartDataGrid)
, new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnItemsPerPageChanged, CoerceTextProperty, true, UpdateSourceTrigger.PropertyChanged));
public Int32 ItemsPerPage
{
get
{
return (Int32)GetValue(ItemsPerPageProperty);
}
set
{
SetValue(ItemsPerPageProperty, value);
}
}
private static void OnItemsPerPageChanged(DependencyObject defectImageControl, DependencyPropertyChangedEventArgs eventArgs)
{
var control = (SmartDataGrid)defectImageControl;
control.callmyInstanceMethod(eventArgs);
}
private static object CoerceTextProperty(DependencyObject d, object value)
{
return value ?? 0;
}
private void callmyInstanceMethod(DependencyPropertyChangedEventArgs e)
{
ItemsPerPage = (Int32)e.NewValue;
}
}
现在,我创建了一个New WPF项目,并在Window1中使用了以下自定义控件。
<Grid>
<sg:SmartDataGrid ItemsPerPage="{Binding ipp}"></sg:SmartDataGrid>
</Grid>
sg:是一个声明的名称空间,用于添加对自定义控件项目的引用。在Window1的.cs文件中,我声明了一个属性。
public partial class Window1 : Window, INotifyPropertyChanged
{
int _ipp;
public int ipp
{ get { return _ipp; } set { _ipp = value; RaisePropertyChanged(); } }
public Window1()
{
ipp = 30;
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
但是,值30没有分配给ItemsPerPage属性。 总是显示0。 如果我直接分配30 ItemsPerPage="30"
。 然后就可以了。
我认为OP的作者不想将datacontext设置为window。 您需要像这样将控件绑定到Window的属性:
ItemsPerPage="{Binding Path=ipp,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window}}"
ipp应该通知属性已更改:
int _ipp;
public int ipp
{
get=>_ipp;
set{
if (value!=_ipp)
{
_ipp=value;
RaisePropertyChanged(nameof(ipp));
}
}
}
void RaisePropertyChanged(string propname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
public Window1()
{
ipp = 30;
InitializeComponent();
}
主要问题是,您未指定Window的DataContext
。
public partial class Window1 : Window
{
public int ipp { get; set; }
public Window1()
{
ipp = 30;
InitializeComponent();
DataContext = this;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.