32

現在、ListView (タブとして) とコンテンツ プロパティをバインドした ContentControl を使用して、非表示のタブを持つタブ コントロールの機能を実現しようとしています。

私はそのトピックについて少し読みましたが、それが正しければ、次のように動作するはずです:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="20.0*"/>
        <ColumnDefinition Width="80.0*"/>
    </Grid.ColumnDefinitions>
    <ListBox Grid.Column="0">
        <ListBoxItem Content="Appearance"/>
    </ListBox>

    <ContentControl Content="{Binding SettingsPage}" Grid.Column="1"/>
</Grid>
.
.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ContentControl x:Key="AppearancePage">
        <TextBlock Text="Test" />
    </ContentControl>
    <ContentControl x:Key="AdvancedPage">
        <TextBlock Text="Test2" />
    </ContentControl>
</ResourceDictionary>

そしてコードビハインドで:

public partial class MainWindow : MetroWindow
  {
    private ContentControl SettingsPage;
    private ResourceDictionary SettingsPagesDict = new ResourceDictionary();

    public MainWindow()
    {
        InitializeComponent();

        SettingsPagesDict.Source = new Uri("SettingsPages.xaml", UriKind.RelativeOrAbsolute);
        SettingsPage = SettingsPagesDict["AppearancePage"] as ContentControl;

エラーはスローされませんが、「テスト」TextBlock は表示されません。

バインドの概念が間違っている可能性があります。正しい方向へのヒントを教えてください。

よろしく

4

1 に答える 1

87

データ バインディングを使用した MVVM (Model-View-ViewModel) アプローチを使用して、ContentControl のコンテンツを動的に変更する方法を示す簡単な例を作成しました。

新しいプロジェクトを作成し、これらのファイルを読み込んで、すべてがどのように機能するかを確認することをお勧めします。

最初に INotifyPropertyChanged インターフェイスを実装する必要があります。これにより、プロパティが変更されたときに UI に通知するプロパティを持つ独自のクラスを定義できます。この機能を提供する抽象クラスを作成します。

ViewModelBase.cs

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}

次に、データ モデルが必要です。簡単にするために、HomePage と SettingsPage の 2 つのモデルを作成しました。両方のモデルには 1 つのプロパティしかありません。必要に応じてさらにプロパティを追加できます。

HomePage.cs

public class HomePage
{
    public string PageTitle { get; set; }
}

SettingsPage.cs

public class SettingsPage
{
    public string PageTitle { get; set; }
}

次に、対応する ViewModel を作成して各モデルをラップします。ビューモデルは ViewModelBase 抽象クラスを継承していることに注意してください。

HomePageViewModel.cs

public class HomePageViewModel : ViewModelBase
{
    public HomePageViewModel(HomePage model)
    {
        this.Model = model;
    }

    public HomePage Model { get; private set; }

    public string PageTitle
    {
        get
        {
            return this.Model.PageTitle;
        }
        set
        {
            this.Model.PageTitle = value;
            this.OnPropertyChanged("PageTitle");
        }
    }
}

SettingsPageViewModel.cs

public class SettingsPageViewModel : ViewModelBase
{
    public SettingsPageViewModel(SettingsPage model)
    {
        this.Model = model;
    }

    public SettingsPage Model { get; private set; }

    public string PageTitle
    {
        get
        {
            return this.Model.PageTitle;
        }
        set
        {
            this.Model.PageTitle = value;
            this.OnPropertyChanged("PageTitle");
        }
    }
}

ここで、各 ViewModel にビューを提供する必要があります。つまり、HomePageView と SettingsPageView です。このために 2 つの UserControls を作成しました。

HomePageView.xaml

<UserControl x:Class="WpfApplication3.HomePageView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
        <TextBlock FontSize="20" Text="{Binding Path=PageTitle}" />
</Grid>

SettingsPageView.xaml

<UserControl x:Class="WpfApplication3.SettingsPageView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TextBlock FontSize="20" Text="{Binding Path=PageTitle}" />
</Grid>

MainWindow の xaml を定義する必要があります。2 つの「ページ」間を移動するのに役立つ 2 つのボタンを含めました。 MainWindow.xaml

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfApplication3"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <DataTemplate DataType="{x:Type local:HomePageViewModel}">
        <local:HomePageView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type local:SettingsPageViewModel}">
        <local:SettingsPageView />
    </DataTemplate>
</Window.Resources>
<DockPanel>
    <StackPanel DockPanel.Dock="Left">
        <Button Content="Home Page" Command="{Binding Path=LoadHomePageCommand}" />
        <Button Content="Settings Page" Command="{Binding Path=LoadSettingsPageCommand}"/>
    </StackPanel>

    <ContentControl Content="{Binding Path=CurrentViewModel}"></ContentControl>
</DockPanel>

MainWindow 用の ViewModel も必要です。しかしその前に、ボタンをコマンドにバインドできるように別のクラスを作成する必要があります。

DelegateCommand.cs

public class DelegateCommand : ICommand
{
    /// <summary>
    /// Action to be performed when this command is executed
    /// </summary>
    private Action<object> executionAction;

    /// <summary>
    /// Predicate to determine if the command is valid for execution
    /// </summary>
    private Predicate<object> canExecutePredicate;

    /// <summary>
    /// Initializes a new instance of the DelegateCommand class.
    /// The command will always be valid for execution.
    /// </summary>
    /// <param name="execute">The delegate to call on execution</param>
    public DelegateCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Initializes a new instance of the DelegateCommand class.
    /// </summary>
    /// <param name="execute">The delegate to call on execution</param>
    /// <param name="canExecute">The predicate to determine if command is valid for execution</param>
    public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
        {
            throw new ArgumentNullException("execute");
        }

        this.executionAction = execute;
        this.canExecutePredicate = canExecute;
    }

    /// <summary>
    /// Raised when CanExecute is changed
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Executes the delegate backing this DelegateCommand
    /// </summary>
    /// <param name="parameter">parameter to pass to predicate</param>
    /// <returns>True if command is valid for execution</returns>
    public bool CanExecute(object parameter)
    {
        return this.canExecutePredicate == null ? true : this.canExecutePredicate(parameter);
    }

    /// <summary>
    /// Executes the delegate backing this DelegateCommand
    /// </summary>
    /// <param name="parameter">parameter to pass to delegate</param>
    /// <exception cref="InvalidOperationException">Thrown if CanExecute returns false</exception>
    public void Execute(object parameter)
    {
        if (!this.CanExecute(parameter))
        {
            throw new InvalidOperationException("The command is not valid for execution, check the CanExecute method before attempting to execute.");
        }
        this.executionAction(parameter);
    }
}

これで、MainWindowViewModel を定義できます。CurrentViewModel は、MainWindow の ContentControl にバインドされるプロパティです。ボタンをクリックしてこのプロパティを変更すると、MainWindow の画面が変わります。MainWindow は、Window.Resources セクションで定義した DataTemplates により、ロードする画面 (ユーザー コントロール) を認識しています。

MainWindowViewModel.cs

public class MainWindowViewModel : ViewModelBase
{
    public MainWindowViewModel()
    {
        this.LoadHomePage();

        // Hook up Commands to associated methods
        this.LoadHomePageCommand = new DelegateCommand(o => this.LoadHomePage());
        this.LoadSettingsPageCommand = new DelegateCommand(o => this.LoadSettingsPage());
    }

    public ICommand LoadHomePageCommand { get; private set; }
    public ICommand LoadSettingsPageCommand { get; private set; }

    // ViewModel that is currently bound to the ContentControl
    private ViewModelBase _currentViewModel;

    public ViewModelBase CurrentViewModel
    {
        get { return _currentViewModel; }
        set
        {
            _currentViewModel = value; 
            this.OnPropertyChanged("CurrentViewModel");
        }
    }

    private void LoadHomePage()
    {
        CurrentViewModel = new HomePageViewModel(
            new HomePage() { PageTitle = "This is the Home Page."});
    }

    private void LoadSettingsPage()
    {
        CurrentViewModel = new SettingsPageViewModel(
            new SettingsPage(){PageTitle = "This is the Settings Page."});
    }
}

最後に、MainWindowViewModel クラスを MainWindow の DataContext プロパティにロードできるように、アプリケーションの起動をオーバーライドする必要があります。

App.xaml.cs

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var window = new MainWindow() { DataContext = new MainWindowViewModel() };
        window.Show();
    }
}

StartupUri="MainWindow.xaml"起動時に MainWindows が 2 つ表示されないように、App.xaml Application タグのコードを削除することもお勧めします。

新しいプロジェクトにコピーして使用できる DelegateCommand および ViewModelBase クラスに注意してください。これは非常に単純な例です。ここここからより良いアイデアを得ることができます

編集 あなたのコメントでは、各ビューと関連する定型コードのクラスを持たなくてもよいかどうかを知りたいと思っていました。私の知る限り、答えはノーです。はい、単一の巨大なクラスを持つことができますが、プロパティ セッターごとに OnPropertyChanged を呼び出す必要があります。これにもかなりの欠点があります。まず、結果のクラスは保守が非常に困難になります。多くのコードと依存関係があります。次に、DataTemplates を使用してビューを「交換」するのは困難です。DataTemplates で ax:Key を使用し、ユーザー コントロールでテンプレート バインディングをハードコーディングすることで、引き続き可能です。本質的には、実際にはコードを大幅に短くしているわけではありませんが、自分にとっては難しくなっています。

あなたの主な不満は、モデルのプロパティをラップするためにビューモデルに非常に多くのコードを書かなければならないことだと思います。T4 テンプレートをご覧ください。一部の開発者は、これを使用してボイラープレート コード (つまり、ViewModel クラス) を自動生成します。私はこれを個人的には使用しません。カスタム コード スニペットを使用して、viewmodel プロパティをすばやく生成します。

もう 1 つのオプションは、Prism や MVVMLight などの MVVM フレームワークを使用することです。私自身は使用したことがありませんが、ボイラープレート コードを簡単に作成できる機能が組み込まれているものがあると聞いたことがあります。

もう 1 つの注意点: 設定をデータベースに保存している場合、Entity Framework などの ORM フレームワークを使用してデータベースからモデルを生成できる可能性があります。つまり、後はビューモデルとビューを作成するだけです。

于 2013-04-11T23:52:46.660 に答える