[英]WPF MainWindow toggle property in UserControl via ViewModel
I have a UserControl within a frame on it's parent window. 我在其父窗口的框架内有一个UserControl。 In the usercontrol, I have a textbox that needs to be edited when a button on the parent window is toggled. 在用户控件中,当切换父窗口上的按钮时,我需要编辑一个文本框。
UserControl.xaml 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 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>
ViewModel 视图模型
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));
}
}
How do I get the data trigger to work properly? 如何使数据触发器正常工作? Is the best way to create another view model for the usercontrol and then communicate the values between the 2 viewmodels? 是为用户控件创建另一个视图模型,然后在两个视图模型之间传递值的最佳方法吗? If so, how would I do that? 如果是这样,我该怎么做?
Is the best way to create another view model for the usercontrol and then communicate the values between the 2 viewmodels? 是为用户控件创建另一个视图模型,然后在两个视图模型之间传递值的最佳方法吗?
The most common way would be for the UserControl
to simply inherit the DataContext
of the parent window so they both can bind to the same property. 最常见的方法是让UserControl
继承父窗口的DataContext
,以便它们都可以绑定到同一属性。
This doesn't work out-of-the-box when you are using a Frame
though. 但是,当您使用Frame
时,这是无法立即使用的。
You could either replace the Frame
with a ContentControl
: 您可以用ContentControl
替换Frame
:
<ToggleButton x:Name="EditButton" IsChecked="{Binding CanEdit}">Edit</ToggleButton>
<ContentControl>
<local:Home />
</ContentControl>
Or you could handle the DataContextChanged
event for the Frame
and set the DataContext
of its Content
explicitly as suggested by @Joe White here: page.DataContext not inherited from parent Frame? 或者,您可以为Frame
处理DataContextChanged
事件,并按@Joe White的建议在此处显式设置其Content
的DataContext
: page.DataContext是否不从父Frame继承?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.