【问题标题】:WPF MainWindow toggle property in UserControl via ViewModel通过 ViewModel 在 UserControl 中的 WPF MainWindow 切换属性
【发布时间】:2017-08-10 13:51:48
【问题描述】:

我在其父窗口的框架内有一个 UserControl。在用户控件中,当父窗口上的按钮被切换时,我有一个文本框需要编辑。

UserControl.xaml

<UserControl.Resources>
    <ResourceDictionary>
        <Style x:Key="TextBoxEdit" TargetType="TextBox">
            <Setter Property="IsReadOnly" Value="True" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding CanEdit}" Value="True">
                    <Setter Property="IsReadOnly" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>

</UserControl.Resources>
<Grid>
    <TextBox
        x:Name="EditTextBox"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Style="{StaticResource TextBoxEdit}"
        Text="Edit me" />
</Grid>

MainWindow.xaml

<Controls:MetroWindow.DataContext>
    <local:ViewModel/>
</Controls:MetroWindow.DataContext>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <ToggleButton x:Name="EditButton" HorizontalAlignment="Center" VerticalAlignment="Top" IsChecked="{Binding CanEdit}">Edit</ToggleButton>
    <Frame Grid.Row="1" Source="Home.xaml" />
</Grid>

视图模型

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool canEdit;
    public bool CanEdit
    {
        get { return canEdit; }
        set
        {
            canEdit = value;
            OnPropertyChanged("CanEdit");
        }
    }

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

如何让数据触发器正常工作?为用户控件创建另一个视图模型然后在两个视图模型之间传递值的最佳方法是什么?如果是这样,我该怎么做?

【问题讨论】:

  • 您使用 Frame 有什么特别的原因吗?
  • 我有一个主窗口,它有一个导航栏,可以将框架的内容更改为不同的用户控件,我认为框架是最好的方法。有更好的选择吗?
  • Home.xaml 是 UserControl 吗?
  • 是的。 Home.xaml 是用户控件

标签: c# wpf xaml mvvm


【解决方案1】:

为用户控件创建另一个视图模型然后在两个视图模型之间传递值的最佳方法是什么?

最常见的方法是让UserControl 简单地继承父窗口的DataContext,这样它们就可以绑定到同一个属性。

但是,当您使用 Frame 时,这不能开箱即用。

您可以将Frame 替换为ContentControl

<ToggleButton x:Name="EditButton" IsChecked="{Binding CanEdit}">Edit</ToggleButton>
<ContentControl>
    <local:Home />
</ContentControl>

或者您可以为Frame 处理DataContextChanged 事件,并按照@Joe White 在此处的建议明确设置其ContentDataContextpage.DataContext not inherited from parent Frame?

【讨论】:

  • 这完全符合我在测试项目中的要求,但我的实际应用程序存在一些问题,我认为我需要重新考虑它的结构。不过你的回答帮了很大的忙,谢谢。
猜你喜欢
  • 2017-07-25
  • 2011-06-22
  • 2017-07-07
  • 2021-04-16
  • 2010-11-23
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
相关资源
最近更新 更多