后期绑定,或从其资源字典访问页面元素

Late Binding, or accessing a page element from its resource dictionary

举个简单的例子,我在资源字典中有一个按钮,我将把它存储在 ContentControl 中。我需要将按钮的可见性 属性 绑定到位于页面上的复选框,但是按钮是在 复选框之前创建的,所以我的 setter 不会工作。

有没有办法在页面初始化后进行绑定?我知道我可以从后面的代码中做到这一点,但是我会有很多按钮, 而且把按钮的部分初始化代码放在不同的位置似乎相当混乱。

<ResourceDictionary>
<button  x:Key = "MyButton">Hi There
<button.Style>
    <Style>
        <Setter Property="IsVisible" Value="false"/>
        <DataTrigger     // myCheckBox doesn't exist yet...
          Binding="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="True">
            <Setter Property="IsVisible" Value="true"/>
        <DataTrigger/>
    </Style>
</button.Style>
</button>
</ResourceDictionary>

<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="1*"/>
    <RowDefinition Height="1*"/>
    <RowDefinition Height="1*"/>
 </Grid.RowDefinitions>

    <CheckBox x:Name = "myCheckBox" Row=1/> //This is made too late to bind my button to

    <ContentControl Content = "{StaticResource MyButton}" Row=2/>

</Grid>

我找到了 lazy loading, where you load objects when you need them, and I've explored making my own binding class 之类的东西,但我不知道该去哪里。

我目前最喜欢的想法是这样的:

xaml:

property="{lateBinding source=whatever path=you.want}"

和一些通用的 c# class 代码:

class lateBinding : Binding
{
    OnPageInitialized()
    {
        SetBinding(myObject, myProperty, myBinding);
    }
}

有什么想法吗?

您的代码稍作改动即可工作

<Window x:Class="WpfApplication11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <Button  x:Key = "MyButton">Hi There
                <Button.Style>
                    <Style TargetType="{x:Type Button}">
                        <Style.Triggers>
                            <DataTrigger  Binding="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="True">
                                <Setter Property="Visibility" Value="Visible"/>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="False">
                                <Setter Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Button.Style>
            </Button>
        </ResourceDictionary>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>

        <CheckBox x:Name = "myCheckBox" Grid.Row="1"/> 

        <ContentControl Content = "{StaticResource MyButton}" Grid.Row="2"/>

    </Grid>
</Window>