我正在使用MVVM框架创建一个WPF应用程序,我已经采用了Josh Smith关于MVVM的文章中的几个特性here...
最重要的是,我将TabControl绑定到ViewModels的ObservableCollection。这意味着我正在使用选项卡式MDI界面,该界面将UserControl显示为TabItem的内容。我在我的应用程序中看到的问题是,当我有几个选项卡并且我在选项卡之间来回切换时,每次我更改选项卡时内容都会被引用。
如果您下载Josh Smith的源代码,您会发现他的应用程序存在同样的问题。例如,单击“查看所有客户”按钮并向下滚动到ListView的底部。然后单击“创建新客户”按钮。当您切换回All Customer视图时,您会注意到ListView滚动回到顶部。如果您切换回New Customer选项卡并将光标放在其中一个TextBox中,然后切换到All Customers选项卡并返回,您会注意到光标现已消失。
我想这是因为我使用的是ObservableCollection,但我无法确定。有没有办法阻止标签的内容在收到焦点时刷新?
修改 我在应用程序上运行探查器时发现了问题。我正在为我的ViewModel定义一个DataTemplate,因此它知道如何在选项卡显示时呈现ViewModel ......就像这样:
<DataTemplate DataType="{x:Type vm:CustomerViewModel}">
<vw:CustomerView/>
</DataTemplate>
因此,每当我切换到其他选项卡时,都必须重新创建ViewModel。我通过将ViewModels的ObservableCollection更改为UserControls的ObservableCollection来临时修复它。但是,如果可能的话,我真的还想使用DataTemplates。有没有办法让DataTemplate工作?
答案 0 :(得分:1)
WPF的默认行为是卸载不可见的项目,包括卸载不可见的TabItems。这意味着当您返回选项卡时,TabItem会重新加载,任何未绑定的内容(例如滚动位置)都将被重置。
有一个很好的网站here,其中包含扩展TabControl的代码,并在切换标签时阻止它销毁它的TabItems,但现在似乎不再存在。
这是我用来防止这个问题的代码。它最初来自该网站,虽然我对它进行了一些更改。切换选项卡时,它会保留ContentPresenter
TabItems,并在您返回页面时使用它重绘TabItem。它占用了更多的内存,但是我发现它在性能上更好,因为TabItem不再需要重新创建它上面的所有控件。
// Extended TabControl which saves the displayed item so you don't get the performance hit of
// unloading and reloading the VisualTree when switching tabs
// Obtained from http://eric.burke.name/dotnetmania/2009/04/26/22.09.28
// and made a some modifications so it reuses a TabItem's ContentPresenter when doing drag/drop operations
[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : System.Windows.Controls.TabControl
{
// Holds all items, but only marks the current tab's item as visible
private Panel _itemsHolder = null;
// Temporaily holds deleted item in case this was a drag/drop operation
private object _deletedObject = null;
public TabControlEx()
: base()
{
// this is necessary so that we get the initial databound selected item
this.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
}
/// <summary>
/// if containers are done, generate the selected item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if (this.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
this.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
UpdateSelectedItem();
}
}
/// <summary>
/// get the ItemsHolder and generate any children
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_itemsHolder = GetTemplateChild("PART_ItemsHolder") as Panel;
UpdateSelectedItem();
}
/// <summary>
/// when the items change we remove any generated panel children and add any new ones as necessary
/// </summary>
/// <param name="e"></param>
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
if (_itemsHolder == null)
{
return;
}
switch (e.Action)
{
case NotifyCollectionChangedAction.Reset:
_itemsHolder.Children.Clear();
if (base.Items.Count > 0)
{
base.SelectedItem = base.Items[0];
UpdateSelectedItem();
}
break;
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
// Search for recently deleted items caused by a Drag/Drop operation
if (e.NewItems != null && _deletedObject != null)
{
foreach (var item in e.NewItems)
{
if (_deletedObject == item)
{
// If the new item is the same as the recently deleted one (i.e. a drag/drop event)
// then cancel the deletion and reuse the ContentPresenter so it doesn't have to be
// redrawn. We do need to link the presenter to the new item though (using the Tag)
ContentPresenter cp = FindChildContentPresenter(_deletedObject);
if (cp != null)
{
int index = _itemsHolder.Children.IndexOf(cp);
(_itemsHolder.Children[index] as ContentPresenter).Tag =
(item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
}
_deletedObject = null;
}
}
}
if (e.OldItems != null)
{
foreach (var item in e.OldItems)
{
_deletedObject = item;
// We want to run this at a slightly later priority in case this
// is a drag/drop operation so that we can reuse the template
this.Dispatcher.BeginInvoke(DispatcherPriority.DataBind,
new Action(delegate()
{
if (_deletedObject != null)
{
ContentPresenter cp = FindChildContentPresenter(_deletedObject);
if (cp != null)
{
this._itemsHolder.Children.Remove(cp);
}
}
}
));
}
}
UpdateSelectedItem();
break;
case NotifyCollectionChangedAction.Replace:
throw new NotImplementedException("Replace not implemented yet");
}
}
/// <summary>
/// update the visible child in the ItemsHolder
/// </summary>
/// <param name="e"></param>
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
UpdateSelectedItem();
}
/// <summary>
/// generate a ContentPresenter for the selected item
/// </summary>
void UpdateSelectedItem()
{
if (_itemsHolder == null)
{
return;
}
// generate a ContentPresenter if necessary
TabItem item = GetSelectedTabItem();
if (item != null)
{
CreateChildContentPresenter(item);
}
// show the right child
foreach (ContentPresenter child in _itemsHolder.Children)
{
child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed;
}
}
/// <summary>
/// create the child ContentPresenter for the given item (could be data or a TabItem)
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
ContentPresenter CreateChildContentPresenter(object item)
{
if (item == null)
{
return null;
}
ContentPresenter cp = FindChildContentPresenter(item);
if (cp != null)
{
return cp;
}
// the actual child to be added. cp.Tag is a reference to the TabItem
cp = new ContentPresenter();
cp.Content = (item is TabItem) ? (item as TabItem).Content : item;
cp.ContentTemplate = this.SelectedContentTemplate;
cp.ContentTemplateSelector = this.SelectedContentTemplateSelector;
cp.ContentStringFormat = this.SelectedContentStringFormat;
cp.Visibility = Visibility.Collapsed;
cp.Tag = (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
_itemsHolder.Children.Add(cp);
return cp;
}
/// <summary>
/// Find the CP for the given object. data could be a TabItem or a piece of data
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
ContentPresenter FindChildContentPresenter(object data)
{
if (data is TabItem)
{
data = (data as TabItem).Content;
}
if (data == null)
{
return null;
}
if (_itemsHolder == null)
{
return null;
}
foreach (ContentPresenter cp in _itemsHolder.Children)
{
if (cp.Content == data)
{
return cp;
}
}
return null;
}
/// <summary>
/// copied from TabControl; wish it were protected in that class instead of private
/// </summary>
/// <returns></returns>
protected TabItem GetSelectedTabItem()
{
object selectedItem = base.SelectedItem;
if (selectedItem == null)
{
return null;
}
if (_deletedObject == selectedItem)
{
}
TabItem item = selectedItem as TabItem;
if (item == null)
{
item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem;
}
return item;
}
}
我经常使用的TabControl模板看起来像这样:
<Style x:Key="TabControlEx_NoHeadersStyle" TargetType="{x:Type local:TabControlEx}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type localControls:TabControlEx}">
<DockPanel>
<!-- This is needed to draw TabControls with Bound items -->
<StackPanel IsItemsHost="True" Height="0" Width="0" />
<Grid x:Name="PART_ItemsHolder" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
答案 1 :(得分:0)
我相信这与绑定模式有关 - 你试过{Binding Mode = OneWay}吗? 绑定到任何'DataSource'对象也会导致同样的问题。
我不确定单向绑定是否是您正在寻找的所需行为,但我会从那里开始。
答案 2 :(得分:0)
它与ObservableCollection无关。这是因为重用了客户视图而不是WPF为每个客户创建一个新视图。
您可以查看 WPF Application Framework (WAF) 的Writer示例应用程序。它也为选项卡式MDI接口实现TabControl,但不会遇到您在帖子中提到的问题。通过为每个文档“选项卡”创建自己的UserControl,可以在Writer中解决该问题。