gpt4 book ai didi

wpf - TabControl 的 ContentTemplate 中的数据绑定(bind)问题

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

我在 tabControl 的内容模板的数据绑定(bind)方面遇到了麻烦。

我有那个课

public class MainWindowViewModel : INotifyPropertyChanged
{
string _text1 = "text1";
string _text2 = "text2";
string _text3 = "text3";

public string Text1
{
get
{
return _text1;
}
set
{
_text1 = value;
}
}

public string Text2
{
get
{
return _text2;
}
set
{
_text2 = value;
}
}

public string Text3
{
get
{
return _text3;
}
set
{
_text3 = value;
}
}

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

我有那个 xaml :
<Window x:Class="LazyBindingTabControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LazyBindingTabControl"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TabControl Height="299" Margin="0,12,0,0" Name="tabControl1" VerticalAlignment="Top">
<TabItem Header="tabItem1" Name="tabItem1">
<TabItem.ContentTemplate>
<DataTemplate>
<TextBlock Name="Text1" Text="{Binding Path=DataContext.Text1}" />
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
<TabItem Header="tabItem2" Name="tabItem2">
<TabItem.ContentTemplate>
<DataTemplate>
<TextBlock Name="Text2" Text="{Binding Path=DataContext.Text2}" />
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
<TabItem Header="tabItem3" Name="tabItem3">
<TabItem.ContentTemplate>
<DataTemplate>
<TextBlock Name="Text3" Text="{Binding Path=DataContext.Text3}" />
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</TabControl>
</Grid>
</Window>

我还在 mainWindow.xaml 的代码隐藏中设置了 dataContext
namespace LazyBindingTabControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
}
}

但是绑定(bind)不成功。如何正确绑定(bind) Text1、Text2 和 Text3 属性。

谢谢。

最佳答案

将 tabitem 内容绑定(bind)到 Text1、Text2、Text3 属性

然后在 TextBlock 部分,像这样绑定(bind)文本

Text={Binding}

所以代码会是这样的
   <TabItem Header="tabItem1" Name="tabItem1" Content="{Binding Text1}">
<TabItem.ContentTemplate>
<DataTemplate>
<TextBlock Name="Text1" Text="{Binding}" />
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>

那应该工作

关于wpf - TabControl 的 ContentTemplate 中的数据绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510114/

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