[英]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.