簡體   English   中英

ItemsControl 中用戶控件的 ItemTemplate - WPF

[英]ItemTemplate for UserControls in ItemsControl - WPF

我的任務是在我們的 WPF 應用程序中實現類似 MDI 的界面。

我創建了這個簡單的 class 作為所有視圖的基礎:

public class BaseView : UserControl, INotifyPropertyChanged
{
        public event PropertyChangedEventHandler? PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string? name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        private ViewType _type = ViewType.Null;
        private string _tabTitle = string.Empty;
        private bool _isSelected = false;

        public ViewType Type { get => _type; set { _type = value; OnPropertyChanged(); } }
        public string TabTitle { get => _tabTitle; set { _tabTitle = value; OnPropertyChanged(); } }
        public bool IsSelected { get => _isSelected; set { _isSelected = value; OnPropertyChanged(); } }
}

接下來,我創建了幾個測試視圖。 它們都是這樣開始的: <local:BaseView...

在main window中,有兩個控件:ItemsControl(用於顯示打開的視圖列表)和ContentControl(用於顯示選中的視圖。)

我將所有打開的視圖存儲在 ObservableCollection: ObservableCollection<BaseView>...中。 我想將它們顯示為列表,因此我創建了 ItemsControl:

<ItemsControl x:Name="mainItemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Padding="2" Margin="2" Tag="{Binding Type}">
                <TextBlock Text="{Binding TabTitle}" Foreground="White"/>
                        </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

當我設置 ItemsControl 的源 ( mainItemsControl.ItemsSource = openedViews; ) 並啟動應用程序時,ItemsControl 顯示每個視圖的內容而不是 ItemTemplate(帶有 TextBlock 的邊框)。 我做錯了什么?

如果我沒理解錯的話,openedViews 集合由 BaseView 組成。 如果是,則 BaseView 是一個 UIElement。
但是數據模板用於呈現非 UIElement。
如果內容接收到 UIElement,則直接按原樣呈現。

一種可能的變體解決方案。
您需要從 BaseView 中刪除 INotifyPropertyChanged 接口。 使用 INotifyPropertyChanged 的實現為您的 BaseView 創建一個數據源。
在 BaseView 中為此源創建 DependencyProperty。

為 openedViews 集合創建一個簡單的輔助容器。
像這樣(偽代碼):

public class SomeContainer 
{
    public BaseDataSource DataSource 
    {
        get => _dataSource;
        set
        {
            _dataSource = null;
            if(View is not null)
            {
                View.DataSource = DataSource;
            }            
        }
    }
    public BaseView View
    {
        get => _view;
        set
        {
            _view = value;
            if(_view is not null)
            {
                _view.DataSource = DataSource;
            }            
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM