【问题标题】:WPF UserControl Triggers from parent window来自父窗口的 WPF UserControl 触发器
【发布时间】:2017-08-10 10:35:20
【问题描述】:

我在其父窗口的框架内有一个 UserControl。在用户控件中,我有一个文本框,当父窗口上的按钮被切换时需要对其进行编辑。

我正在尝试使用触发器来做到这一点 用户控件.xaml

<UserControl.Resources>
    <ResourceDictionary>
        <Style x:Key="TextBoxEdit" TargetType="TextBox">
            <Setter Property="IsReadOnly" Value="True" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=EditButton}" 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>

当用户控件中有一个名为 EditButton 的按钮时,这可以正常工作,但是当 EditButton 在父窗口中时是否可以这样做?

MainWindow.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <ToggleButton x:Name="EditButton" HorizontalAlignment="Center" VerticalAlignment="Top">Edit</ToggleButton>
    <Frame Grid.Row="1" Source="Home.xaml" />
</Grid>

据我了解,用户控件的数据上下文将从父窗口继承,因此是否可以像绑定到按钮的触发器一样简单,或者我必须使用视图模型/按钮命令?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    ...但是当 EditButton 在父窗口中时可以这样做吗?

    不,不是因为ButtonTextBox属于不同的命名范围。

    据我了解,用户控件的数据上下文将从父窗口继承,因此是否可以像绑定到按钮的触发器一样简单,或者我必须使用视图模型/按钮命令?

    您应该将ToogleButtonIsChecked 属性绑定到视图模型的源属性,然后将触发器绑定到相同的源属性:

    <DataTrigger Binding="{Binding IsChecked}" Value="True">
    ...
    

    确保视图模型正确实现INotifyPropertyChanged接口:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

    【讨论】:

    • 谢谢。我已经用我的视图模型更新了我的问题,我该去哪里?
    • 如果您还有其他问题,请提出新问题。
    • 请在此处查看新问题:stackoverflow.com/questions/45615689/… 谢谢。
    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多