[英]UserControl's DependencyProperty is null when UserControl has a DataContext
[英]How: Bind to a UserControl's DependencyProperty, when the UserControl has a DataContext?
我的問題是沒有在UserControl
連接DependencyProperties
。 這不是問題。 當我將UserControl
的按鈕綁定到名為TargetCommand
的UserControl
的DependencyProperty
時,當我在UserControl
上設置DataContext
時,綁定會中斷。 我已經嘗試過使用FindAncestor
,當然還有ElementName
,但它們只在UserControl
上沒有DataContext
時才能運行。
有沒有解決的辦法?
例:
主窗口
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid>
<UserControls:MyUserControl
TargetCommand="{Binding PathToCommand}"
DataContext="{Binding PathToSomeModel}" />
MyUserControl代碼背后
public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty TargetCommandProperty =
DependencyProperty.Register( "TargetCommand", typeof( ICommand ), typeof( MyUserControl ) );
public ICommand TargetCommand
{
get { return (ICommand)GetValue( TargetCommandProperty ); }
set { SetValue( TargetCommandProperty, value ); }
}
MyUserControl - Xaml
<UserControl x:Name="root">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=TargetCommand}" />
<Button Command="{Binding Path=TargetCommand, ElementName=root}" />
只要未在MainWindow中的MyUserControl上設置DataContext,MyUserControl中綁定的RelativeSource和ElementName方法都會正確連接。 設置DataContext后都不起作用。
有沒有辦法在MyUserControl上設置DataContext,並仍然保留DependencyProperty綁定到TargetCommand?
您的PathToCommand
在哪里定義? 如果我正確地閱讀您的示例,它應該在VisualTree中比UserControl更高。 在這種情況下,您將綁定到包含PathToCommand的DataContext並綁定到DataContext.PathToCommand
任何控件
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid x:Name="PART_Root">
<UserControls:MyUserControl
TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />
不確定我是否遺漏了一些東西,但為什么在設置DataContext時需要DependencyProperty? 為什么模型中沒有可以直接從按鈕綁定的屬性?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.