Как изменить свойство элемента шаблона ресурса, используя только XAML? - PullRequest
0 голосов
/ 27 октября 2019

Основная идея состоит в том, чтобы иметь кнопку со значком по умолчанию "yes.png" и текстом в ней "Accept", но иметь возможность изменять эти два свойства, используя только XAML (в процессе проектирования, без компиляции).

Текущее окно XAML с областью внизу с двумя кнопками:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary>
            <Style x:Key="tb1" TargetType="{x:Type Button}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Border BorderThickness="1" BorderBrush="#000" Padding="0">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Image Source="Files/Icons/no.png" Margin="10,0,0,0" Height="16" Width="16"></Image>
                                    <TextBlock Grid.Column="1" Margin="10" VerticalAlignment="Center">Cancel</TextBlock>
                                </Grid>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="Margin" Value="0,10,10,10"></Setter>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Border BorderThickness="0, 1, 0, 0" BorderBrush="#e7e7e7" HorizontalAlignment="Stretch" Padding="0,0,0,0" VerticalAlignment="Bottom" Height="61">
            <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
                <Button x:Name="b_Accept" Style="{StaticResource tb1}"></Button> <!-- How to change an icon to "yes.png" and TextBlock's content to "Accept"? -->
                <Button x:Name="b_Cancel" Style="{StaticResource tb1}"></Button>
            </StackPanel>
        </Border>
    </Grid>
</Window>

Результат:

img1

Пожалуйста,

  1. Как можно изменить значок второй кнопки на "no.png" ( Свойство источника ) и текст TextBlock ( Содержимое ) на"Cancel" ( только с использованием XAML и , а не пользовательским контролем )?

  2. Что было бы очень правильным способом (самый простой?)? Например, в этой записи мы можем использовать DataTemplate , но, возможно, мы этого не хотим, потому что DataTemplate изменяет весь элемент, в то время как нам нужно только одно свойство.

Хотя, я прав, что для этой цели доступно только dependency property (C #), который ожидает компиляцию?

Спасибо

1 Ответ

2 голосов
/ 27 октября 2019

Вы можете создать свой собственный класс Button или присоединенное свойство, чтобы расширить Button:

public class IconControl : DependencyObject
{
  #region IconUri attached property

  public static readonly DependencyProperty IconUriProperty = DependencyProperty.RegisterAttached(
    "IconUri", typeof(ImageSource), typeof(IconControl), new PropertyMetadata(default(ImageSource)));

  public static void SetIconUri([NotNull] DependencyObject attachingElement, ImageSource value)
  {
    attachingElement.SetValue(IconControl.IconUriProperty, value);
  }

  public static ImageSource GetIconUri([NotNull] DependencyObject attachingElement) => (ImageSource) attachingElement.GetValue(IconControl.IconUriProperty);

  #endregion

  #region Label attached property

  public static readonly DependencyProperty LabelProperty = DependencyProperty.RegisterAttached(
    "Label", typeof(String), typeof(IconControl), new PropertyMetadata(default(String)));

  public static void SetLabel([NotNull] DependencyObject attachingElement, String value)
  {
    attachingElement.SetValue(IconControl.LabelProperty, value);
  }

  public static String GetLabel([NotNull] DependencyObject attachingElement) => (String) attachingElement.GetValue(IconControl.LabelProperty);

  #endregion
}

Изменено Style для Button:

<Style x:Key="IconButtonStyle"
       TargetType="{x:Type Button}">

  <!-- Set the default values -->
  <Setter Property="IconControl.IconUri" Value="/Files/Icons/no.png"/>
  <Setter Property="IconControl.Label" Value="Cancel"/>

  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Border BorderThickness="1"
                BorderBrush="#000"
                Padding="0">
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="Auto" />
              <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(IconControl.IconUri)}"
                   Margin="10,0,0,0"
                   Height="16"
                   Width="16" />
            <TextBlock Grid.Column="1"
                       Margin="10"
                       VerticalAlignment="Center"
                       Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(IconControl.Label)}" />
          </Grid>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
  <Setter Property="Margin"
          Value="0,10,10,10"></Setter>
</Style>

Использование:

<!-- Override the default content -->
<Button Style="{StaticResource IconButtonStyle}"
        IconControl.IconUri="/Files/Icons/yes.png"
        IconControl.Label="Accept" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...