C# 如何将命令和contexrt从UserControl绑定到MainView UWP MVVM
标签所在的表单以及包装在按钮中的用户控件。我需要通过单击用户控件中的按钮来更改文本块中的文本。我没有使用任何MVVM框架。 主要XAML:C# 如何将命令和contexrt从UserControl绑定到MainView UWP MVVM,c#,mvvm,uwp,datacontext,C#,Mvvm,Uwp,Datacontext,标签所在的表单以及包装在按钮中的用户控件。我需要通过单击用户控件中的按钮来更改文本块中的文本。我没有使用任何MVVM框架。 主要XAML: <Page.DataContext> <local:MainViewModel /> </Page.DataContext> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<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>
我创建了一个空的用户控件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属性?您的主要问题是如何使用
ControlViewModel
UserControls
如ControlView
一般不应将其自身的DataContext
设置为某个专门的视图模型,而是从其父元素继承DataContext
假设让控件继承DataContext
,则可以向其添加依赖项属性并将命令绑定到此属性:
<local:ControlView YourCommand="{Binding SetText}" />
ControlView.xaml:
<UserControl ... Name="uc">
<Button Command="{Binding YourCommand, ElementName=uc}" />
谢谢!你的回答很有帮助!
<local:ControlView YourCommand="{Binding SetText}" />
<UserControl ... Name="uc">
<Button Command="{Binding YourCommand, ElementName=uc}" />