[英]How to bind command and contexrt from UserControl to MainView UWP MVVM
There is a form in which the label is located, as well as a user control wrapped in a button.有一个标签所在的表单,以及一个包裹在按钮中的用户控件。 I need to change the text in the TextBlock by clicking the button in the user control.
我需要通过单击用户控件中的按钮来更改 TextBlock 中的文本。 I didn't use any MVVM frameworks.
我没有使用任何 MVVM 框架。 Main XAML:
主要 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>
User Conrol Xaml:用户控制 Xaml:
<Grid>
<Button Width="300" Height="100" FontSize="50" Command="{Binding}"
VerticalAlignment="Center" HorizontalAlignment="Center" Content="Print chart" />
</Grid>
Main VM:主虚拟机:
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));
}
}
And I create an empty user control VN:我创建了一个空的用户控件 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?
}
So how to correctly implement commands from user control to main view, fe SetText property?那么如何正确实现从用户控件到主视图的命令,fe SetText 属性呢?
Your main issue is there is the use of the ControlViewModel
.您的主要问题是使用
ControlViewModel
。 UserControls
such as ControlView
should generally speaking not set their own DataContext
to some specialized view model but rather inherit the DataContext
from their parent element.像
ControlView
这样的UserControls
通常不应该将它们自己的DataContext
设置为某些专门的视图模型,而是应该从它们的父元素继承DataContext
。
Assuming you let the control inherit the DataContext
, you could add a dependency property to it and bind the command to this one:假设您让控件继承
DataContext
,您可以向它添加一个依赖属性并将命令绑定到这个:
<local:ControlView YourCommand="{Binding SetText}" />
ControlView.xaml:控件视图.xaml:
<UserControl ... Name="uc">
<Button Command="{Binding YourCommand, ElementName=uc}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.