簡體   English   中英

綁定到 UserControl XAML 中的依賴屬性

[英]Binding to a Dependency Property inside UserControl XAML

我想重用一個控件,但其中一個場景需要上下文菜單,而其他場景則不需要。 這是我的嘗試。

public partial class RP8Grid : UserControl {

    public bool UseContextMenu {
        get { return (bool)GetValue(UseContextMenuProperty); }
        set { SetValue(UseContextMenuProperty, value); }
    }

    // Using a DependencyProperty as the backing store for UseContextMenu.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty UseContextMenuProperty =
        DependencyProperty.Register("UseContextMenu", typeof(bool), typeof(RP8Grid), new PropertyMetadata(false));

        public RP8Grid() {
            InitializeComponent();
        }
    }

並在 XAML 中使用屬性:

<ctls:RP8Grid UseContextMenu="False"/>

現在我無法解決的部分,我如何訪問 UserControl 內的 UseContextMenu? 我嘗試了以下方法:

<DataGrid>
  <DataGrid.ContextMenu>
    <ContextMenu IsEnabled="{Binding UseContextMenu,RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor}}">
  </DataGrid.ContextMenu>
</DataGrid>

結果:

無法找到引用“RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1'的綁定源

如果您想要的只是有時擺脫ContextMenu ,這將起作用:

<DataGrid 
    >
    <DataGrid.Style>
        <Style TargetType="DataGrid" BasedOn="{StaticResource {x:Type DataGrid}}">
            <Style.Triggers>
                <DataTrigger 
                    Binding="{Binding UseContextMenu, RelativeSource={RelativeSource AncestorType=UserControl}}"
                    Value="True"
                    >
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu 
                                >
                                <MenuItem Header="Test Item" />
                                <MenuItem Header="Test Item" />
                                <MenuItem Header="Test Item" />
                                <MenuItem Header="Test Item" />
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Style>
</DataGrid>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM