Binding ContentControl动态内容的内容
本文关键字:动态 ContentControl Binding | 更新日期: 2023-09-27 18:08:37
我目前正在尝试通过使用ListView(作为选项卡)和绑定内容属性的ContentControl来实现隐藏选项卡的tabcontrol功能。
我读了一些关于这个主题的书,如果我没有弄错的话,它应该是这样工作的:
<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;
虽然它没有抛出错误,但它不显示"Test" TextBlock。
很可能我理解错了绑定的概念,请给我一个正确的方向提示。
对
好的,我已经提出了一个简单的例子,向您展示如何使用数据绑定的MVVM(模型-视图- 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);
}
}
}
我们现在需要有数据模型。为了简单起见,我创建了2个模型——主页和settingpage。两个模型都只有一个属性,你可以根据需要添加更多的属性。
HomePage.cs
public class HomePage
{
public string PageTitle { get; set; }
}
SettingsPage.cs
public class SettingsPage
{
public string PageTitle { get; set; }
}
然后我创建相应的ViewModels来包装每个模型。注意,视图模型继承自我的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提供Views。也就是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>
我们现在需要为主窗口定义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>
我们还需要一个主窗口的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是绑定到主窗口上的ContentControl的属性。当我们通过单击按钮更改此属性时,主窗口上的屏幕将发生变化。主窗口知道加载哪个屏幕(用户控制),因为我在窗口中定义了datatemplate。参考资料部分。
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();
}
}
移除App.xaml Application标签中的StartupUri="MainWindow.xaml"
代码也是一个好主意,这样我们就不会在启动时得到2个主windows。
注意,DelegateCommand和ViewModelBase类只能被复制到新项目中并使用。这只是一个非常简单的例子。你可以从这里和这里得到更好的想法
编辑在你的评论中,你想知道是否有可能不必为每个视图和相关的样板代码都有一个类。据我所知,答案是否定的。是的,你可以有一个巨大的类,但是你仍然需要为每个Property setter调用OnPropertyChanged。这种方法也有一些缺点。首先,生成的类很难维护。会有很多代码和依赖项。其次,很难使用datatemplate来"交换"视图。通过在DataTemplates中使用x:Key并在usercontrol中硬编码模板绑定,这仍然是可能的。从本质上讲,你并没有真正使你的代码变得更短,但你会使你自己更难。
我猜你主要的抱怨是不得不在你的视图模型中编写这么多代码来包装你的模型属性。看看T4模板。一些开发人员使用它来自动生成样板代码(例如ViewModel类)。我个人不使用这个,我使用自定义代码片段来快速生成viewmodel属性。
另一个选择是使用MVVM框架,如Prism或MVVMLight。我自己没有使用过,但我听说其中一些内置了使样板代码更简单的功能。
另一点需要注意的是:如果您将设置存储在数据库中,则可以使用ORM框架(如Entity framework)从数据库生成模型,这意味着您剩下的就是创建视图模型和视图了。