我已经创建了一个小的wpf测试项目来演示我的问题。该项目包含一个wpf窗口。此窗口仅包含TabControl
。这个TabControl
的页面是从绑定的ItemSource
动态创建的。
我的XAML:
<Window x:Name="window" x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:TestWpf"
Title="MainWindow" Height="350" Width="525">
<TabControl x:Name="tabControl" BorderThickness="0" ItemsSource ="{Binding MediaLists, ElementName=window, NotifyOnSourceUpdated=True}">
<TabControl.ItemTemplate>
<DataTemplate DataType="{x:Type vm:MediaList}">
<TextBlock Padding="2" Text="{Binding MediaTypeName}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate x:Name="contentTemplate" DataType="{x:Type vm:MediaList}">
<DataGrid x:Name="dgMediaList" ItemsSource="{Binding Medias, BindsDirectlyToSource=True}" DockPanel.Dock="Top" AutoGenerateColumns="False" HorizontalGridLinesBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}" VerticalGridLinesBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}">
<DataGrid.Columns>
<DataGridTextColumn x:Name="clmAuthor" Header="Author" Binding="{Binding Author}" IsReadOnly="True" CanUserReorder="False" />
<DataGridTextColumn x:Name="clmTitle" Header="Title" Binding="{Binding Title}" IsReadOnly="True" CanUserReorder="False" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Window>
而背后的代码是这样的:
public partial class MainWindow : Window
{
private readonly ObservableCollection<MediaList> m_MediaLists = new ObservableCollection<MediaList>();
public ObservableCollection<MediaList> MediaLists { get { return m_MediaLists; } }
public MainWindow()
{
InitializeComponent();
MediaList cdList = new MediaList("CDs");
cdList.Medias.Add(new Media("AuthorCdA", "TitleCdA1"));
cdList.Medias.Add(new Media("AuthorCdA", "TitleCdA2"));
cdList.Medias.Add(new Media("AuthorCdB", "TitleCdB1"));
cdList.Medias.Add(new Media("AuthorCdB", "TitleCdB2"));
MediaList bookList = new MediaList("Books");
bookList.Medias.Add(new Media("AuthorBookA", "TitleBookA1"));
bookList.Medias.Add(new Media("AuthorBookA", "TitleBookA2"));
bookList.Medias.Add(new Media("AuthorBookB", "TitleBookB1"));
bookList.Medias.Add(new Media("AuthorBookB", "TitleBookB2"));
m_MediaLists.Add(cdList);
m_MediaLists.Add(bookList);
}
}
以MediaList
为例:
public class MediaList : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private readonly ObservableCollection<Media> m_Medias = new ObservableCollection<Media>();
public string MediaTypeName { get; private set; }
public ObservableCollection<Media> Medias { get { return m_Medias; }}
public MediaList(string typeName)
{
MediaTypeName = typeName;
}
}
和Media
像这样:
public class Media
{
public string Author { get; private set; }
public string Title { get; private set; }
public Media(string author, string title)
{
Author = author;
Title = title;
}
}
所以这一切都很好,你可以在这里看到:
现在的问题是:如何为每个DataGrid
保存TabPage
的布局?当我在TabPage
s之间切换时,所有页面的列宽保持相同,但排序总是完全丢失。
我想绑定DataGrid
的列宽以及用户在MediaList
实例的成员中更改的多列排序设置。
因此,为了简化这个问题,让我们专注于列宽。我将成员添加到MediaList
类:
private DataGridLength m_WidthAuthor = DataGridLength.SizeToCells;
private DataGridLength m_WidthTitle = DataGridLength.SizeToCells;
public DataGridLength WidthAuthor
{
get { return m_WidthAuthor; }
set
{
if (value == m_WidthAuthor) return;
m_WidthAuthor = value;
OnPropertyChanged("WidthAuthor");
}
}
public DataGridLength WidthTitle
{
get { return m_WidthTitle; }
set
{
if (value == m_WidthTitle) return;
m_WidthTitle = value;
OnPropertyChanged("WidthTitle");
}
}
并尝试在xaml中设置绑定:
<DataGridTextColumn x:Name="clmAuthor" ... Width="{Binding WidthAuthor, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" />
<DataGridTextColumn x:Name="clmTitle" ... Width="{Binding WidthTitle, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" />
但不幸的是,这不起作用。我读过几篇SO文章,认为双向绑定很困难。但即使是单向绑定对我也不起作用。 (我对wpf / mvvm很新,所以也许我在这里使用了一些错误的词......)
在调试器输出窗口中,我可以看到宽度绑定的这些错误消息:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=WidthAuthor; DataItem=null; target element is 'DataGridTextColumn' (HashCode=54916642); target property is 'Width' (type 'DataGridLength')
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=WidthTitle; DataItem=null; target element is 'DataGridTextColumn' (HashCode=40809782); target property is 'Width' (type 'DataGridLength')
因此,如果有人能告诉我如何为每个DataGrid
保存那些TabPage
属性,我会非常高兴。这个问题的焦点在于宽度。排序可能是一个新问题的主题(请注意,绑定列的SortDirection
可能不适用于多列排序)
编辑:我已将diag:PresentationTraceSources.TraceLevel=High
添加到Binding
表达式中的一列Width
,并在调试输出中找到这些消息:
System.Windows.Data Warning: 62 : BindingExpression (hash=18270086): Attach to System.Windows.Controls.DataGridTextColumn.Width (hash=37671782)
System.Windows.Data Warning: 64 : BindingExpression (hash=18270086): Use Framework mentor <null>
System.Windows.Data Warning: 67 : BindingExpression (hash=18270086): Resolving source
System.Windows.Data Warning: 69 : BindingExpression (hash=18270086): Framework mentor not found
System.Windows.Data Warning: 65 : BindingExpression (hash=18270086): Resolve source deferred
我太新wpf了解Framework mentor
是什么,如果这真的应该是null
。
我在this article的帮助下解决了这个问题。不幸的是,我的wpf知识仍然很低,我无法解释(以及所提到的文章的作者)幕后发生的事情,如果这真的是一个很好的解决方案。
所以这就是我所做的:
其中一个问题是DataContext
不是继承到DataGridTextColumn
。所以目的是将其存储在代理中。
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return GetValue(DATA_PROPERTY); }
set { SetValue(DATA_PROPERTY, value); }
}
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DATA_PROPERTY =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
我将这个本地资源添加到xaml中的DataGrid
:
<DataGrid.Resources>
<vm:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>
最后我修改了DataGridTextColum
宽度的绑定表达式:
Width="{Binding Data.WidthAuthor, Source={StaticResource proxy}....
etvoilá,它有效!
我将继续研究如何为多列排序执行此操作。如果我找不到解决办法,我会提出一个新问题。如果没有人在接下来的日子里为此添加解决方案,我会接受我自己的答案。
更新:我解决了多列排序问题here。