在设置DataContext以便于绑定时以编程方式实例化新的UserControl

时间:2018-12-30 19:12:50

标签: c# wpf mvvm data-binding

MahApps-Material mashup demo开始,我尝试使用按钮单击事件从“视图”中创建新的TabItem。目前,CustomTabItem将显示绑定到FancyObject中某个属性的文本(已从我的FancyTabViewModel投放到视图中)。但是我把DataContext,依赖属性或Binding做错了。

    public void NewTabOnClick(object sender, RoutedEventArgs e)
    {
        // create my new object from Models 
        FancyObject fo = new FancyObject();
        // create the INofify VM and pass it my object
        // the VM has a public VMFancyObject property to serve the fo
        FancyTabViewModel fvm = new FancyTabViewModel(fo);
        // create the new UserControl and set its context to the VM
        CustomTabItem newTab = new CustomTabItem() {
            Header = "New tab"
        };
        newTab.DataContext = fvm;
        MainWindowTabs.Items.Add(newTab);
    }

在我的<TabItem x:Class="MyProject.Views.CustomTabItem"中有一个这样绑定的标签:<Label Content="{Binding VMFancyObject.SomeList.Count}"/>

我希望看到在FancyObject的构造函数中创建的列表的默认计数。但是,在创建新标签并将其添加到dragablz:TabablzControl之后,我只是看到一个空白标签。

我也尝试过<Label DataContext="{Binding Path=DataContext.FancyTabViewModel,RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" Content="{Binding VMFancyObject.SomeList.Count}" HorizontalAlignment="Left" Margin="341,196,0,0" Foreground="Black" Background="#FF97FF02"/>

0 个答案:

没有答案