wpf - WPF 窗口/框架/页面
问题描述
我有一个窗口,其中包含一个网格,其中包含:标签和框架。框架包含一个页面。该页面有一个按钮和一个标签。
两个标签(在窗口和页面上)都绑定到相同的字符串属性,最初可以正常工作。
按钮(在页面上)更改了字符串属性,我希望更改窗口上的标签和页面上的标签。
问题是它只更改页面上的标签而不更改窗口上的标签。有没有办法让页面上的按钮更改其父窗口中的元素?另外,如果有解释为什么会发生这种情况,我将不胜感激。
窗口 Xaml:
<Window.DataContext>
<ViewModel:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Content="{Binding SourceTitleHeader, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Foreground="Red">
</Label>
</Grid>
<Frame Grid.Row="1" Grid.Column="0" Source="\Views\Page1.xaml">
</Frame>
</Grid>
页面 Xaml:
<Page.DataContext>
<ViewModel:MainWindowViewModel/>
</Page.DataContext>
<StackPanel Margin="10">
<Label Content="{Binding SourceTitleHeader, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="0 0 0 20">
</Label>
<Button Content="ChangeLabel" Width="100" Height="30" HorizontalAlignment="Left"
Command="{Binding Refresh_Screen_Command}">
</Button>
</StackPanel>
解决方案
您有两个不同的对象用于DataContext
窗口和页面,请确保您使用的是相同的对象。
<Window.Resources>
<ResourceDictionary>
<local:MainWindowViewModel x:Key="ViewModel" />
</ResourceDictionary>
</Window.Resources>
<Grid DataContext="{StaticResource ViewModel}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Content="{Binding SourceTitleHeader, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Foreground="Red">
</Label>
</Grid>
<Frame Grid.Row="1" Grid.Column="0">
<Frame.Content>
<local:Page1 DataContext="{StaticResource ViewModel}" />
</Frame.Content>
</Frame>
</Grid>
推荐阅读
- string - 从字符串中取出所有单词
- javascript - Json 数据集错误:无法读取未定义的属性“父”和无法设置属性“_node”为空
- r - R:对数据框进行难以描述的转换
- c++ - 保存 JSON 的双重自递归变体?
- ubuntu - 在 Raspberry Pi 3 Model B+ 上安装 Ubuntu Server 20.04 期间的屏幕失真
- python - set_index() 后数据帧多索引中的值消失
- javascript - 使用 Fetch API 递归返回分页输出
- html - 用户输入文本框显示在同一页面上
- excel - 使用 with 语句粘贴并在错误显示 msgbox 上
- node.js - 使用 yarn 从库中更新 RubyGem 依赖项