我有一個 WPF 應用程式,我在其中將檔案視圖實體動態加載到TabControl. 該視圖有一個ToolBarwith some ToggleButton,我用它來控制該視圖中某些元素的可見性,如下所示(僅顯示相關元素):
<UserControl x:Class="MyProject.View.Views.DocumentView" ...>
...
<ToolBar>
<ToggleButton x:Name="togglePropInspector" ... />
...
</ToolBar>
...
<Border Visibility={Binding ElementName=togglePropInspector, Path=IsChecked, Converter={StaticResource BoolToVisibilityConverter}}">
...
</Border>
</UserControl>
我發現這有點整潔,因為所有內容都在視圖內處理,并且不需要向視圖模型(或后面的代碼)添加代碼。但是,問題是現在檢查一個選項卡上的切換按鈕會在視圖的所有實體中檢查它,而不僅僅是當前選項卡。這基本上適用于狀態未以任何方式系結到視圖模型的所有元素。有沒有辦法解決這個問題而不必向視圖模型添加代碼?
為了完整起見,這是我如何加載視圖的相關部分:
<TabControl ItemsSource="{Binding Documents}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type viewModels:DocumentViewModel}">
<local:DocumentView />
</DataTemplate>
</TabControl.Resources>
</TabControl>
uj5u.com熱心網友回復:
TabControl具有用于所有TabItem實體的單個內容主機。當分配給TabItem.Content屬性的資料模型具有相同的資料型別時,TabControl將重用相同的DataTemplate,這意味著相同的元素實體,僅使用來自資料系結的更改資料進行更新。
要更改重用控制元件的狀態,您必須顯式訪問控制元件,或者通過臨時更改 的資料型別來強制TabControl重新應用:ContentTemplateContent
<TabControl SelectionChanged="TabControl_SelectionChanged" />
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var tabControl = sender as TabControl;
var tabItemContainer = tabControl.ItemContainerGenerator.ContainerFromItem(tabControl.SelectedItem) as TabItem;
object currentContent = tabItemContainer.Content;
tabItemContainer.Content = null;
// Defer and leave the context to allow the TabControl to handle the new data type (null).
// The content switch shouldn't be noticable in the GUI.
Dispatcher.InvokeAsync(() => tabItemContainer.Content = currentContent);
}
您還可以為每個選項卡使用專用資料型別。這樣TabControl就自動強制切換了DataTemplate。
最干凈的解決方案是將 系結ToggleButton到資料模型。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450812.html
上一篇:我似乎無法更改Xamarin.CommunityToolkitTabView選項卡的順序。有沒有辦法做到這一點?
