【发布时间】:2018-09-23 06:03:41
【问题描述】:
我有一个DataGrid,它的标题中有一个绑定的 UI 控件。绑定到视图模型中的字段。网格位于TabControl 内。当网格位于选项卡控件的初始选项卡上时,一切正常。
但是,当网格不在初始选项卡上时,似乎没有发生绑定。没有控制台输出,没有调用值转换器,没有报告任何跟踪级别的日志。
这是一个简单的、可重现的例子:
查看模型
public class ViewModel : INotifyPropertyChanged
{
private string _camel = "Bertie";
public string Camel
{
get => _camel;
set
{
if (value == _camel) return;
_camel = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainWindow.xaml
<Window x:Class="ThingsWithHumps.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:thingsWithHumps="clr-namespace:ThingsWithHumps"
mc:Ignorable="d"
Height="350" Width="350">
<Window.DataContext>
<thingsWithHumps:ViewModel/>
</Window.DataContext>
<TabControl>
<!-- This TabItem prevents the TextBlock being bound -->
<TabItem Header="Troublesome tab"/>
<TabItem Header="Humps">
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<!-- Troublesome binding -->
<TextBlock Text="{Binding Path=DataContext.Camel,
UpdateSourceTrigger=PropertyChanged,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}" />
</DataGridTemplateColumn.Header>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</TabItem>
</TabControl>
</Window>
MainWindow.xaml.cs
namespace ThingsWithHumps
{
public partial class MainWindow
{
public MainWindow() => InitializeComponent();
}
}
【问题讨论】:
-
在这个例子中你的虚拟机没有实现
INotifyPropertyChanged。 -
谢谢迈克尔;刚刚更新了代码和问题,但同样的问题仍然存在。
标签: wpf xaml wpfdatagrid tabcontrol