gpt4 book ai didi

c# - WPF:绑定(bind)选项卡控件

转载 作者:行者123 更新时间:2023-12-03 10:27:53 25 4
gpt4 key购买 nike

我正在使用 MVVM,我正在尝试绑定(bind) TabControl's ItemsSource ,我使用了这段代码:

<TabControl ItemsSource="{Binding ProjectComponents}"
SelectedIndex="{Binding SelectedMenu, Mode=TwoWay}" Grid.Column="1" Margin="5">

对于 View 模型:
projectComponents = new ObservableCollection<TabItem>();
projectComponents.Add(new TabItem()
{

Content = new ProjectComponentsView()
{
DataContext = new ProjectClientHandlerViewModel()
}
});

我在 Silverlight 中使用了它项目,它工作得很好,但在 WPF ,不知道为什么 TabItem的内容不显示。

编辑:

我将我的代码编辑为:

看法:
 <TabControl ItemsSource="{Binding ProjectComponents}" SelectedIndex="{Binding SelectedMenu, Mode=TwoWay}" Grid.Column="1" Margin="5">
<TabControl.ContentTemplate>
<DataTemplate >
<this:ProjectComponentsView DataContext="{Binding}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>

查看型号:
projectComponents = new ObservableCollection<ProjectComponentViewModel>();
projectComponents.Add(new ProductViewsHandlerViewModel());

在哪里 ProjectComponentViewModelProductViewsHandlerViewModel 的基类,但它仍然无法正常工作。

最佳答案

这是一个让您入门的快速示例

public class MainVm : VMBase
{
public ObservableCollection<TabVM> Items { get; set; }
public VMBase SelectedItem {get;set;}
public MainVm()
{
Items = new ObservableCollection<TabVM>()
{
new TabVM(){Header="A",Content = new SomeVm()},
new TabVM(){Header="B",Content = new SomeVm()},
new TabVM(){Header="C",Content = new SomeVm()},
new TabVM(){Header="D",Content = new OtherVm()}
};
}
}

public class TabVM : VMBase
{
public string Header { get; set; }
public VMBase Content { get; set; }
}

public class SomeVm : VMBase{}
public class OtherVm : VMBase{}
public class VMBase { }


<TabControl ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type local:SomeVm}">
<TextBlock>SomeVm Template</TextBlock>
</DataTemplate>
<DataTemplate DataType="{x:Type local:OtherVm}">
<TextBlock>OtherVm Template</TextBlock>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"></TextBlock>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl Content="{Binding Content}"></ContentControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>

根据 ViewModel 选择模板键入我们在资源中设置的内容,您还应该使用 ViewModel表示 TabItem ,即 TabVM在上面的片段中。

ItemTemplate您设置标题模板的选项卡控件的 ContentTemplate你把 ContentControl并绑定(bind)其 ContentContent TabVM 的属性(property).

不要忘记执行 INotifyPropertyChanged .

关于c# - WPF:绑定(bind)选项卡控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29686844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com