WPF,Control无法通过ControlTemplate中的基础Control从CommandParameter访问ElementName

5t7ly7z5  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(115)

我需要一些帮助,这段代码,我可以绑定imageBrush的名称:Border.InputBindings的CommandParameter中的“ImageBrush1F”。
第一个代码工作,但第二个不工作。
在我使用ControlTemplate更改设计后,它无法在ControlTemplate中找到“ImageBrush1F”,使用ControlTemplate时如何实现相同的结果?这是新的设计代码:

<Border Tag="AstronautWoman"
        Style="{StaticResource AvatarBorder}"
        HorizontalAlignment="Center"
        VerticalAlignment="Top"
        Margin="0 0 20 0">
    <Border.InputBindings>
        <MouseBinding Command="{Binding ImageSelectCommand}"
                      CommandParameter="{Binding ElementName=ImageBrush1F}"
                      MouseAction="LeftClick"/>
    </Border.InputBindings>

    <Ellipse>
        <Ellipse.Fill>
            <ImageBrush x:Name="ImageBrush1F" ImageSource="/Images/Avatar/astronaut_woman.png"/>
        </Ellipse.Fill>
    </Ellipse>
</Border>


<RadioButton Name="Astronaut"
             Tag="BlockInternet"
             Command="{Binding ImageSelectCommand}"
             CommandParameter="{Binding ElementName=ImageBrush1M}"
             Height="100" Width="100"
             Margin="0 0 20 30">
    <RadioButton.Template>
        <ControlTemplate TargetType="RadioButton">
            <Border Name="border"
                    BorderBrush="#2B1058" BorderThickness="2"
                    Height="{TemplateBinding Height}"
                    Width="{TemplateBinding Width}" 
                    CornerRadius="50"
                    Background="White">
                <Ellipse>
                    <Ellipse.Fill>
                        <ImageBrush x:Name="ImageBrush1M" ImageSource="/Images/Avatar/astronaut.png"/>
                    </Ellipse.Fill>
                </Ellipse>
            </Border>
    </RadioButton.Template>
</RadioButton>
gwo2fgha

gwo2fgha1#

我认为你应该在更高的级别上定义ImageBrush,比如Window.Resources,并引用它。如果你迫切需要在RadioButton中完成它,我不建议你使用,但你可以像下面这样使用未使用的RadioButton.Background属性。

<RadioButton Name="Astronaut"
             Tag="BlockInternet"
             Command="{Binding ImageSelectCommand}"
             CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Background}"
             Height="100" Width="100"
             Margin="0 0 20 30">
    <RadioButton.Background>
        <ImageBrush x:Name="ImageBrush1M" ImageSource="/Images/Avatar/astronaut.png"/>
    </RadioButton.Background>
    <RadioButton.Template>
        <ControlTemplate TargetType="RadioButton">
            <Border Name="border"
                    BorderBrush="#2B1058" BorderThickness="2"
                    Height="{TemplateBinding Height}"
                    Width="{TemplateBinding Width}"
                    CornerRadius="50"
                    Background="White">
                <Ellipse Fill="{TemplateBinding Background}"/>
            </Border>
        </ControlTemplate>
    </RadioButton.Template>
</RadioButton>

相关问题