【问题标题】:Set frame content when a button is clicked using MVVM使用 MVVM 单击按钮时设置帧内容
【发布时间】:2017-11-02 09:45:09
【问题描述】:

我是 MVVM 模式的新手,但我了解其中一些。我目前遇到的问题是我想在按下按钮时打开一个页面,使用 MVVM 模式。当按下六个按钮之一时,一个命令可以给我按下的按钮的名称。我的问题是我不知道按下按钮时如何设置框架的内容。

    <StackPanel>
        <Button Content="Page 1" x:Name="Page1"
                Command="{Binding SimpleCommand, Source={StaticResource ViewModelBase}}" 
                CommandParameter="{Binding Name, ElementName=Page1}"/>
        <Button Content="Page 2" x:Name="Page2"
                Command="{Binding SimpleCommand, Source={StaticResource ViewModelBase}}" 
                CommandParameter="{Binding Name, ElementName=Page2}"/>
    </StackPanel>

上面是现在的 XAML 代码。简单的命令就是在按钮上写出名字

 <Frame x:Name="MainFrame" Grid.Column="1" Grid.Row="1"
           Content="{Binding Name, Converter={StaticResource Converter}, ElementName=Page1}" 
           NavigationUIVisibility="Hidden"/>

上面是我要更改内容的框架。在编译时我可以设置它应该打开的页面。我想在运行时设置内容,我使用按钮名称。 转换器只是 IValueConverter,我在其中设置它应该显示的页面。

【问题讨论】:

  • 嗨,欢迎来到 SO。请添加您的代码。
  • 嘿。现在添加代码。我希望它会有所帮助。

标签: c# wpf mvvm


【解决方案1】:

我解决这个问题的方法不是使用框架,而是使用ContentPresenter。您始终可以在您的Frame 中插入ContentPresenter。请记住,Frame 不会继承 DataContext,所以我会避免使用它。
首先,让我们创建一个BaseViewModel 作为视图的起点。

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}  

现在我们有了基础,让我们创建一个MainViewModel

public class MainViewModel : BaseViewModel
{
    private BaseViewModel selectedViewModle;

    public BaseViewModel SelectedViewModel
    {
        get { return selectedViewModle; }
        set { selectedViewModle = value; OnPropertyChanged(nameof(SelectedViewModel)); }
    }
}  

此时我们的MainViewModel 有一个带有SelectedViewModel 的属性,这就是我们要用于导航的属性。
假设
我假设您对命令以及如何使用它们有一定的应用知识。
这是您的 Navigate command 方法的代码示例:

void navigate(object parameter)
{
    SelectedViewModel = new DetailsViewModel();
}  

这是DetailsViewModel的代码:

public class DetailsViewModel : BaseViewModel
{
    //your code with properties and methods here
}  


现在让我们设置视图:
<UserControl ...>
    <Grid>
        <ContentPresenter Content="{Binding .}"/>
    </Grid>
</UserControl>  

现在在 UserControl 的资源标签中包含 DataTemplate

<DataTemplate DataType="{x:Type vm:DetailsViewModel}">
    <Grid .../>
</DataTemplate>  

此时,您将在屏幕上为您呈现数据模板的内容。

【讨论】:

  • 嘿。会尝试让它工作。但是谢谢:)。很高兴有人有解决方案,所以我可以走得更远:)。但是谢谢,伙计。祝你有美好的一天:)。
猜你喜欢
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 2011-12-18
  • 1970-01-01
相关资源
最近更新 更多