在我的应用程序中,此顶部有3个菜单, - 添加和修改。我正在使用MahApps.Metro。 我从这个link得到了这个TabControl方法。这是menu.xaml, -
<Controls:MetroAnimatedSingleRowTabControl Controls:TabControlHelper.IsUnderlined="True"
ItemsSource="{Binding FieldViewModels}"
SelectedItem="{Binding SelectedFieldViewModel}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type local:AddFieldViewModel}">
<view:AddFieldView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ModifyFieldViewModel}">
<view:ModifyFieldView/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ScriptFieldViewModel}">
<view:ScriptFieldView/>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}" />
<Setter Property="Controls:ControlsHelper.HeaderFontSize" Value="18" />
</Style>
</TabControl.ItemContainerStyle>
</Controls:MetroAnimatedSingleRowTabControl>
在我有的MenuViewModel.cs中, -
public MenuViewModel()
{
fieldViewModels = new ObservableCollection<ITabViewModel>();
}
public ObservableCollection<ITabViewModel> FieldViewModels
{
get
{
fieldViewModels.Add(new AddFieldViewModel { Header = "Add" });
fieldViewModels.Add(new ModifyFieldViewModel { Header = "Modify" });
fieldViewModels.Add(new ScriptFieldViewModel { Header = "Script" });
return fieldViewModels;
}
private set { }
}
public ITabViewModel SelectedFieldViewModel
{
get
{
if (selectedFieldViewModel==null)
{
selectedFieldViewModel= FieldViewModels[0];
}
return selectedFieldViewModel;
}
set
{
if (!EqualityComparer<ITabViewModel>.Default.Equals(selectedFieldViewModel,value))
{
selectedFieldViewModel= value;
RaisePropertyChanged("selectedFieldViewModel");
}
}
}
此处ITabViewModel
是具有属性标题的标记接口。
现在我的问题是关于标签更改,视图持有最后的状态。说在AddFieldView
我有一些下拉菜单并选择了一些内容。然后,在该页面中没有做任何事情,我移动到Modify选项卡并返回。然后我看到下拉仍然保持最后的选择。基本上在选项卡更改时,视图不会使用ViewModel刷新(与菜单更改重新加载页面的网页不同。)
如何在选项卡更改时使用ViewModel刷新视图?
修改
我尝试按如下方式更改SelectedFieldViewModel
属性,但后来视图没有变化,可能是因为这违反了ObservableCollection, -
public ITabViewModel SelectedFieldViewModel
{
get
{
if (selectedFieldViewModel == null)
{
selectedFieldViewModel = fieldViewModels[0];
}
return selectedFieldViewModel;
}
set
{
if (!EqualityComparer<ITabViewModel>.Default.Equals(selectedFieldViewModel, value))
{
switch (value.Header)
{
case "Add":
selectedFieldViewModel = new AddFieldViewModel() { Header = "Add" };
break;
case "Modify":
selectedFieldViewModel = new ModifyFieldViewModel() { Header = "Modify" };
break;
case "Script":
selectedFieldViewModel = new ScriptFieldViewModel() { Header = "Script" };
break;
default:
break;
}
RaisePropertyChanged("SelectedFieldViewModel");
}
}
}