更改按钮外观/图标

时间:2018-09-26 08:49:57

标签: c# wpf xaml model-view-controller

我想更改按钮上的图标。这是我的按钮的xaml:

<Button Name="InitPurgeBtn" Click="InitPurgeClick">
    <Rectangle Width="35" Height="45" Margin="0,0,0,0">
        <Rectangle.Fill>
            <VisualBrush Stretch="Fill" Visual="{StaticResource InitIcon}" />
        </Rectangle.Fill>
    </Rectangle>
</Button>

问题是我不知道如何访问控制器中按钮矩形的Visual属性以通过“ PurgeIcon”更改“ InitIcon” 我所有的图标都在xaml中实现:

<Viewbox x:Key="ExtinctionIcon" Stretch="Uniform" x:Shared="False">
    <Canvas Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
        <Path Width="40" Height="40"  Stretch="Fill" Fill="{Binding Foreground, 
            RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" 
            Data="M15,24H17V22H15M16.56,{...}24H13V22H11M7,24H9V22H7V24Z"/>
    </Canvas>
</Viewbox>

编辑:

我更改了按钮,他现在就像这样:

<Button Name="InitBtn" Style="{StaticResource RoundButton}" Width="70" Height="70" 
    Click="InitPurgeClick" Content="{StaticResource InitIcon}">                                  
</Button>

我想更改代码中的图标,因此尝试设置Content属性:

InitBtn.Content = "{StaticResource ExtinctionIcon}";

但是这种方式只是将我的图标替换为字符串“ StaticResource ..”

3 个答案:

答案 0 :(得分:1)

您可以使用Content属性。

 <Button Name="InitPurgeBtn" Width="100" Height="40">
        <Button.Content>
            <Image Source=".\Icon.PNG"/>
        </Button.Content>
    </Button>

答案 1 :(得分:1)

已更新以反映新信息

您使用一些新信息更新了您的问题,这些新信息改变了很多事情。

由于您尝试更新代码中的Button.Content,因此将无法使用MarkupExtension。仅在最初创建视图时才评估MarkupExtensions(XAML中{}内的内容)。之后,它们的行为就像常规字符串一样,因此尝试在代码中设置一个将不起作用。

要在代码中设置值,您将需要手动执行MarkupExtension正在执行的操作;通过名称查找资源,然后直接设置值。您可以使用以下代码(假设引用了InitPurgeBtn)来做到这一点。

InitPurgeBtn.Content = InitPurgeBtn.FindResource("ExtinctionIcon");

上一个答案

您应该可以直接将图标添加到Content的{​​{1}},因为它似乎被定义为某处的资源(由于{{ 1}}属性)。您的代码并未确切显示在何处,因此我不能允许它在不做任何修改的情况下工作。

Button

要使此功能正常运行,必须在按钮可访问的某个位置定义x:Key资源,这意味着在按钮的祖先或<Button Name="InitPurgeBtn" Width="100" Height="40" Content="{StaticResource ExtinctionIcon}" /> 中。

使用ExtinctionIcon定义资源的事实似乎表明它被设计为完全以这种方式使用,因为可视元素可能可以同时在多个地方托管。 >


或者,您可以直接将图标复制并嵌入到按钮中。

App.xaml

答案 2 :(得分:0)

如果只需要一个(xaml)图标,则可以将按钮的content属性绑定到图标资源。

下面的控件提供了增强的显示-xaml图标和一个文本标题,包括该图标的两种颜色和对禁用状态的支持。

MyXamlIconHost.cs

public enum CaptionPosition { None, ToLeftOfIcon, AboveIcon, ToRightOfIcon, BelowIcon }

public enum IconSize { Small, Medium, Large, XLarge, XxLarge }

public class myXamlIconHost : Control
{
    private static readonly Brush DefaultForeground = new SolidColorBrush(Color.FromRgb(32,32,32));
    private static readonly Brush DefaultHighlight = Brushes.DarkOrange;
    private static readonly Brush DefaultDisabledForeground = new SolidColorBrush(Color.FromRgb(192, 192, 192));
    private static readonly Brush DefaultDisabledHighlight = new SolidColorBrush(Color.FromRgb(128, 128, 128));

    static myXamlIconHost()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(myXamlIconHost), new FrameworkPropertyMetadata(typeof(myXamlIconHost)));
    }

    public FrameworkElement XamlIcon
    {
        get { return (FrameworkElement)GetValue(XamlIconProperty); }
        set { SetValue(XamlIconProperty, value); }
    }

    public static readonly DependencyProperty XamlIconProperty =
        DependencyProperty.Register("XamlIcon", typeof(FrameworkElement), typeof(myXamlIconHost), new PropertyMetadata(null));

    public IconSize IconSize
    {
        get { return (IconSize)GetValue(IconSizeProperty); }
        set { SetValue(IconSizeProperty, value); }
    }

    public static readonly DependencyProperty IconSizeProperty =
        DependencyProperty.Register("IconSize", typeof(IconSize), typeof(myXamlIconHost), new PropertyMetadata(IconSize.Medium));

    public string Caption
    {
        get { return (string)GetValue(CaptionProperty); }
        set { SetValue(CaptionProperty, value); }
    }

    public static readonly DependencyProperty CaptionProperty =
        DependencyProperty.Register("Caption", typeof(string), typeof(myXamlIconHost), new PropertyMetadata(null));

    public CaptionPosition CaptionPosition
    {
        get { return (CaptionPosition)GetValue(CaptionPositionProperty); }
        set { SetValue(CaptionPositionProperty, value); }
    }

    public static readonly DependencyProperty CaptionPositionProperty =
        DependencyProperty.Register("CaptionPosition", typeof(CaptionPosition), typeof(myXamlIconHost), new PropertyMetadata(CaptionPosition.ToRightOfIcon));

    public Brush StandardForeground
    {
        get { return (Brush)GetValue(StandardForegroundProperty); }
        set { SetValue(StandardForegroundProperty, value); }
    }

    public static readonly DependencyProperty StandardForegroundProperty =
        DependencyProperty.Register("StandardForeground", typeof(Brush), typeof(myXamlIconHost), new PropertyMetadata(DefaultForeground));

    public Brush StandardHighlight
    {
        get { return (Brush)GetValue(StandardHighlightProperty); }
        set { SetValue(StandardHighlightProperty, value); }
    }

    public static readonly DependencyProperty StandardHighlightProperty =
        DependencyProperty.Register("StandardHighlight", typeof(Brush), typeof(myXamlIconHost), new PropertyMetadata(DefaultHighlight));

    public Brush DisabledForeground
    {
        get { return (Brush)GetValue(DisabledForegroundProperty); }
        set { SetValue(DisabledForegroundProperty, value); }
    }

    public static readonly DependencyProperty DisabledForegroundProperty =
        DependencyProperty.Register("DisabledForeground", typeof(Brush), typeof(myXamlIconHost), new PropertyMetadata(DefaultDisabledForeground));

    public Brush DisabledHighlight
    {
        get { return (Brush)GetValue(DisabledHighlightProperty); }
        set { SetValue(DisabledHighlightProperty, value); }
    }

    public static readonly DependencyProperty DisabledHighlightProperty =
        DependencyProperty.Register("DisabledHighlight", typeof(Brush), typeof(myXamlIconHost), new PropertyMetadata(DefaultDisabledHighlight));
}

// ==============================================================================================================================================

public class myXamlIconSizeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        const int defaultSize = 24;

        if (!(value is IconSize))
            return defaultSize;

        var iconSizeValue = (IconSize)value;

        switch (iconSizeValue)
        {
            case IconSize.Small:
                return defaultSize * 2 / 3;
            case IconSize.Large:
                return defaultSize * 3 / 2;
            case IconSize.XLarge:
                return defaultSize * 2;
            case IconSize.XxLarge:
                return defaultSize * 5 / 2;
            default:
                return defaultSize;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

MyXamlIconHost.xaml

<Style TargetType="{x:Type ctrl:myXamlIconHost}">
    <Setter Property="Focusable" Value="False" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="Padding" Value="0" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ctrl:myXamlIconHost}">
                <Grid Margin="{TemplateBinding Padding}">
                    <Grid.Resources>
                        <ctrl:myXamlIconSizeConverter x:Key="IconSizeConverter" />
                    </Grid.Resources>

                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>

                    <TextBlock x:Name="PART_CaptionTextBlock"
                               Grid.Row="1"
                               Grid.Column="0"
                               Margin="8,0,8,0"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center"
                               Foreground="{TemplateBinding StandardForeground}"
                               Text="{TemplateBinding Caption}" />

                    <!--  Set DataContext to "self" so that the Xaml Icon item can bind to the Foreground and BorderBrush properties  -->
                    <ContentControl x:Name="PART_IconPresenter"
                                    Grid.Row="1"
                                    Grid.Column="1"
                                    Width="{TemplateBinding IconSize,
                                                            Converter={StaticResource IconSizeConverter}}"
                                    Height="{TemplateBinding IconSize,
                                                             Converter={StaticResource IconSizeConverter}}"
                                    HorizontalAlignment="Center"
                                    VerticalAlignment="Center"
                                    BorderBrush="{TemplateBinding StandardHighlight}"
                                    Content="{TemplateBinding XamlIcon}"
                                    DataContext="{Binding RelativeSource={RelativeSource Self}}"
                                    Focusable="False"
                                    Foreground="{TemplateBinding StandardForeground}" />
                </Grid>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter TargetName="PART_CaptionTextBlock" Property="Foreground" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisabledForeground}" />
                        <Setter TargetName="PART_IconPresenter" Property="BorderBrush" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisabledHighlight}" />
                        <Setter TargetName="PART_IconPresenter" Property="Foreground" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisabledForeground}" />
                    </Trigger>

                    <Trigger Property="CaptionPosition" Value="None">
                        <Setter TargetName="PART_CaptionTextBlock" Property="Visibility" Value="Collapsed" />
                    </Trigger>

                    <Trigger Property="CaptionPosition" Value="ToLeftOfIcon">
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Column" Value="0" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Row" Value="1" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Margin" Value="8,0,8,0" />
                    </Trigger>

                    <Trigger Property="CaptionPosition" Value="ToRightOfIcon">
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Column" Value="2" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Row" Value="1" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Margin" Value="8,0,8,0" />
                    </Trigger>

                    <Trigger Property="CaptionPosition" Value="AboveIcon">
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Column" Value="1" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Row" Value="0" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Margin" Value="8,0,8,4" />
                    </Trigger>

                    <Trigger Property="CaptionPosition" Value="BelowIcon">
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Column" Value="1" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Grid.Row" Value="2" />
                        <Setter TargetName="PART_CaptionTextBlock" Property="Margin" Value="8,4,8,0" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>

用法示例

<Window ... >
    <Window.Resources>
        <Grid x:Key="TestIcon" x:Shared="False" Background="Transparent">
            <Path Stretch="Fill" Data=" M 0,0 M 100,100 M 0,0 L 0,100 L 100,100 L 100,60 L 90,60 L 90,90 L 10,90 L 10,10 L 90,10 L 90,40 L 100,40 L 100,0 z" Fill="{ Binding Foreground, FallbackValue=Cyan}"/>
            <Path Stretch="Fill" Data=" M 0,0 M 100,100 M 70,45 L 100,45 L 100,55 L 70,55 z" Fill="{ Binding BorderBrush, FallbackValue=Magenta}"/>
        </Grid>
    </Window.Resources>

    <Button HorizontalAlignment="Center" VerticalAlignment="Center">
        <Border Background="LightBlue">
            <ctrls:myXamlIconHost Caption="The Caption" XamlIcon="{StaticResource TestIcon}" IconSize="XxLarge" Padding="20" />
        </Border>
    </Button>
</Window>