首页 > 解决方案 > WPF 窗口/框架/页面

问题描述

我有一个窗口,其中包含一个网格,其中包含:标签和框架。框架包含一个页面。该页面有一个按钮和一个标签。

两个标签(在窗口和页面上)都绑定到相同的字符串属性,最初可以正常工作。

按钮(在页面上)更改了字符串属性,我希望更改窗口上的标签和页面上的标签。

问题是它只更改页面上的标签而不更改窗口上的标签。有没有办法让页面上的按钮更改其父窗口中的元素?另外,如果有解释为什么会发生这种情况,我将不胜感激。

带有输出屏幕截图的 ViewModel

窗口 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>

标签: wpfxamlwindow

解决方案


您有两个不同的对象用于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>

推荐阅读