gpt4 book ai didi

c# - WPF 数据模板绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 13:37:11 25 4
gpt4 key购买 nike

我发现在 WPF TabControl 中使用 ContentTemplate/DataTemplate 时,我的绑定(bind)将不再起作用。

我举了一个小例子来说明:

<Window x:Class="HAND.BindingExample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindingExample" Height="506" Width="656"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
<Grid>
<TabControl HorizontalAlignment="Left" Height="381" VerticalAlignment="Top" Width="608">
<TabItem Header="TabItem">
<Label Content="{Binding Path=myString}"/>
</TabItem>
<TabItem Header="TabItem">
<TabItem.ContentTemplate>
<DataTemplate>
<Label Content="{Binding Path=myString}"/>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</TabControl>
</Grid>
</Window>

Tab1 按预期工作,Tab2 为空。

背后的代码:

using System.Windows;

namespace HAND
{
public partial class BindingExample : Window
{
public string myString { get; set; }

public BindingExample()
{
myString = "Hello Stackoverflow";

InitializeComponent();
}
}
}

最佳答案

您未正确使用 ContentTemplate 属性。来自ContentControl.ContentTemplate Property MSDN 上的页面:

Gets or sets the data template used to display the content of the ContentControl.

因此,在设置该属性时,还需要将Content属性设置为某种数据源:

<TabControl>
<TabItem Header="TabItem">
<Label Content="{Binding Path=myString}"/>
</TabItem>
<TabItem Header="TabItem" Content="{Binding Path=myString}">
<TabItem.ContentTemplate>
<DataTemplate>
<Label Content="{Binding}" />
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</TabControl>

关于c# - WPF 数据模板绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534021/

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