【问题标题】:How to bind command and contexrt from UserControl to MainView UWP MVVM如何将命令和上下文从 UserControl 绑定到 MainView UWP MVVM
【发布时间】:2023-04-03 07:45:01
【问题描述】:

有标签所在的表单,以及包裹在按钮中的用户控件。我需要通过单击用户控件中的按钮来更改 TextBlock 中的文本。我没有使用任何 MVVM 框架。 主要 XAML:

    <Page.DataContext>
    <local:MainViewModel />
</Page.DataContext>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="553*" />
        <ColumnDefinition Width="197*" />
    </Grid.ColumnDefinitions>
    <local:ControlView Grid.Column="1" HorizontalAlignment="Stretch"
                       VerticalAlignment="Stretch" />
    <TextBlock Grid.Column="0" Foreground="Black" FontSize="50" VerticalAlignment="Stretch"
               HorizontalAlignment="Stretch" Text="{Binding UserText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
    
</Grid>

用户控制 Xaml:

<Grid>
    <Button Width="300" Height="100" FontSize="50" Command="{Binding}"
            VerticalAlignment="Center" HorizontalAlignment="Center" Content="Print chart" />
</Grid>

主虚拟机:

 public class MainViewModel : INotifyPropertyChanged
{
    public MainViewModel()
    {
        
        SetText = new RelayCommand(SetUserText);
    }

    public ICommand SetText { get; set; }

    public string UserText { get; set; }

    
    public event PropertyChangedEventHandler PropertyChanged;

    private void SetUserText()
    {
        UserText = "Hello World!";
        RaisePropertyChanged(nameof(UserText ));
    }

    
    protected void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}

我创建了一个空的用户控件 VN:

public class ControlViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    // And what should I do here?
}

那么如何正确实现从用户控件到主视图的命令,f.e SetText 属性?

【问题讨论】:

    标签: c# mvvm uwp datacontext


    【解决方案1】:

    您的主要问题是使用了ControlViewModelUserControlsControlView 通常不应该将自己的DataContext 设置为某些专门的视图模型,而是从其父元素继承DataContext

    假设你让控件继承DataContext,你可以给它添加一个依赖属性并将命令绑​​定到这个:

    <local:ControlView YourCommand="{Binding SetText}" />
    

    ControlView.xaml:

    <UserControl ... Name="uc">
        <Button Command="{Binding YourCommand, ElementName=uc}" />
    

    【讨论】:

    • 谢谢!你的回答很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 2020-03-10
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多