我的DataContext已更改。如何正确执行绑定

时间:2016-02-10 14:52:00

标签: c# wpf xaml datacontext icommand

我正在使用UserControl,我有基于自定义类的TreeView,构建如下:

-ConnectionModel

--- SchemaModel

----- SchemaCollection

------- TableModel的

TreeView就像一个魅力。

我在TreeView中单击TableModel项后添加了ContextMenu。 然后我想创建绑定到Command" SelectFromTab"我在SideBar()类中声明(对于此视图是ModelView)。

如何在SideBar类中正确地使用Binding to SelectFromTab命令? 现在ContextMenu的DataContext被设置为" TableModel"。

我的观点(完整.xaml)

<Page
  ....
  xmlns:local="clr-namespace:ProgDB4.ViewModel"
  xmlns:models="clr-namespace:ProgDB4.Model"

  xmlns:ProgDB4="clr-namespace:ProgDB4" x:Name="page" x:Class="ProgDB4.ViewModel.SideBar"

  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="300"
  Title="SideBar">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="20"/>
    </Grid.RowDefinitions>
    <TabControl Grid.Row="0" x:Name="SideBarTabControl" SelectionChanged="SideBarTabControl_SelectionChanged">
        <TabItem Header="Map" Content="Mapa"/>
        <TabItem Header="History" Content="History"/>
        <TabItem Header="Aliases" x:Name="tab_aliases"   Width="52">
            <Grid>
                <TreeView x:Name="AliasTree" ItemsSource="{Binding TVData}">
                    <TreeView.Resources >
                        <HierarchicalDataTemplate DataType="{x:Type models:ConnectionModel}"  ItemsSource="{Binding schemas}">
                            <TextBlock Text="{Binding alias}" />
                        </HierarchicalDataTemplate>

                        <HierarchicalDataTemplate DataType="{x:Type models:SchemaModel}"      ItemsSource="{Binding schema_collections}">
                            <TextBlock Text="{Binding SCHEMA_NAME}" />
                        </HierarchicalDataTemplate>


                        <HierarchicalDataTemplate DataType="{x:Type models:SchemaCollection}"  ItemsSource="{Binding collection}">
                            <TextBlock Text="{Binding SCHEMA_COLLECTION_NAME}" />
                        </HierarchicalDataTemplate>

                        <DataTemplate DataType="{x:Type models:TableModel}" >
                            <TextBlock Text="{Binding TABLE_NAME}" PreviewMouseRightButtonDown="TextBlock_PreviewMouseRightButtonDown" >

                                <TextBlock.ContextMenu>
                                    <ContextMenu>
                                        <MenuItem Header="SELECT TOP 100"  Command ="{Binding SelectFromTab}"/>
                                        <MenuItem Header="SELECT TOP 1000"/>
                                        <MenuItem Header="Display indexes"/>
                                        <MenuItem Header="Display columns"/>
                                    </ContextMenu>
                                </TextBlock.ContextMenu>

                            </TextBlock>
                        </DataTemplate>
                    </TreeView.Resources>
                </TreeView>

            </Grid>
        </TabItem>
    </TabControl>
    <TextBox x:Name="SearchBox" Text="Search..." Height="20" Grid.Row="1" TextChanged="SearchBox_TextChanged" GotFocus="SearchBox_GotFocus" LostFocus="SearchBox_LostFocus"/>
</Grid>

我的SideBar类

public partial class SideBar : Page, INotifyPropertyChanged
{
    private List<ConnectionModel> _TVData;
    public MainViewModel mainViewModelContext;
    public TreeView tmpAliasTree = new TreeView();

    public ICommand _SelectFromTab;
    public ICommand SelectFromTab
    {
        get
        {
            MessageBox.Show("ddd");
            return _SelectFromTab;

        }
        set { if (value != _SelectFromTab) { _SelectFromTab = value; } }
    }

    public SideBar( MainViewModel mainViewContext )
    {
        TreeViewBase = new List<ConnectionModel>(ConnectionUtilities.LoadObservableConnections());
        mainViewModelContext = mainViewContext ;

        InitializeComponent();

        this.DataContext = this  ;

        // this.SelectFromTab = mainViewModelContext.SelectFromTab  ;

        var loadSideBar = Task.Factory.StartNew(async () => { await LoadSideBar(); });
        loadSideBar.Wait();

        OnPropertyChanged("TVData");
    }

2 个答案:

答案 0 :(得分:1)

ContextMenuDataContext的{​​{1}}不一样。您可以手动设置它。

UserControl

并且您的命令将正常工作。

答案 1 :(得分:0)

我可以理解,问题是将TableModel项的ContextMenu命令绑定到它的父(UserControl)DataContext“SelectFromTab”命令。如果是这样,那么当绑定模式是FindAncestor时,您需要执行RelativeSource绑定。但是这里有一些小问题,TabModel项目的可视化树中不存在ContextMenu。请将下一个示例作为研究的起点。

<强> XAML

<Style TargetType="SetHereTheTypeOfDataContextMenyTargetControl">
        <Setter Property="dataGridCreateColumnAndBindIteFromCodeBehind:Attached.ParentDataContextToTag" Value="True"></Setter>
         <Setter Property="ContextMenu">
             <Setter.Value>
                <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                    <MenuItem Header="MenuItem One"
                              Command="{Binding CmdMenuItemOne}" />
                    <MenuItem Header="MenuItem Two" 
                              Command="{Binding CmdMenuItemTwo}" />
                </ContextMenu>
            </Setter.Value>
         </Setter>
     </Style>

附加财产代码

public class Attached
{

    public static readonly DependencyProperty SetDataGridDataContextToTagProperty = DependencyProperty.RegisterAttached(
        "SetDataGridDataContextToTag", typeof (bool), typeof (Attached), new PropertyMetadata(default(bool), SetParentDataContextToTagPropertyChangedCallback));

    public static void SetSetDataGridDataContextToTag(DependencyObject element, bool value)
    {
        element.SetValue(SetDataGridDataContextToTagProperty, value);
    }

    public static bool GetSetDataGridDataContextToTag(DependencyObject element)
    {
        return (bool) element.GetValue(SetDataGridDataContextToTagProperty);
    }

    private static void SetParentDataContextToTagPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        PerformDataContextToTagAssignment(dependencyObject as FrameworkElement, (bool)args.NewValue);
    }

    private static void PerformDataContextToTagAssignment(FrameworkElement sender, bool isAttaching)
    {
        var control = sender;
        if (control == null) return;
        if (isAttaching == false)
        {
            control.Tag = null;
        }
        else
        {
            var dataGrid = control.FindParent<PutHereTheTypeOfVisualParentWhichDataContextYouNeed>();
            if (dataGrid == null) return;
            control.Tag = dataGrid.DataContext;
        }
    }
}

帮助者代码

public static class VisualTreeHelperExtensions
{
    public static T FindParent<T>(this DependencyObject child) where T : DependencyObject
    {
        while (true)
        {
            //get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);

            //we've reached the end of the tree
            if (parentObject == null) return null;

            //check if the parent matches the type we're looking for
            T parent = parentObject as T;
            if (parent != null)
                return parent;
            child = parentObject;
        }
    }
}

如果您需要有关代码的帮助,请与我们联系。

问候。