WPF: индивидуальный стиль для элементов - PullRequest
1 голос
/ 28 февраля 2011

C #

public class MyButton : Button
{
    public Color MyColor { get; set; }
}

WPF:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication3">
    <Window.Resources>
        <Style TargetType="my:MyButton">
            <Setter Property="Background" Value="SkyBlue"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <CheckBox Content="Individual Mode" x:Name="ModeCheckBox" Grid.Row="0" />
        <my:MyButton Content="B1" x:Name="myB1" Grid.Row="1" MyColor="Aqua"/>
        <my:MyButton Content="B2" x:Name="myB2" Grid.Row="2"/>
        <my:MyButton Content="B3" x:Name="myB3" Grid.Row="3" MyColor="Green"/>
    </Grid>
</Window>

Теперь. Я хочу, чтобы все мои кнопки были синими (это нормальный режим), а также для каждого отдельного «MyColor» (это индивидуальный режим).

Возможно ли это?

Как только я пытаюсь установить элемент стиля (Background в моем случае) по коду, я нарушил логику стиля, и он больше не переключается обратно.

Ответы [ 2 ]

2 голосов
/ 28 февраля 2011

Вам необходимо определить стиль по умолчанию для элемента управления MyButton; который будет храниться в файле Themes/Generic.xaml.

    <Style TargetType="{x:Type local:MyButton}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="MyColor" Value="Blue"/>
    </Style>

Эта кнопка теперь по умолчанию будет иметь свойство MyColor, установленное на Blue, если явно не указано иное для каждого экземпляра элемента управления.

    <Grid>
        <local:MyButton Height="30" VerticalAlignment="Top">MyButtonDefault</local:MyButton>
        <local:MyButton Height="30" VerticalAlignment="Bottom" MyColor="Red">MyButtonRed</local:MyButton>
    </Grid>

Ниже приведен источник MyButton, в котором я изменяю свойство Background для этого примера на основе свойства MyColor.

    public class MyButton : Button
    {
        static MyButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MyButton), new FrameworkPropertyMetadata(typeof(MyButton)));
        }

        public Color MyColor
        {
            get { return (Color)GetValue(MyColorProperty); }
            set { SetValue(MyColorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyColor.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyColorProperty =
            DependencyProperty.Register("MyColor", typeof(Color), typeof(MyButton), new PropertyMetadata(new PropertyChangedCallback(Change)));

         private static void Change(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            MyButton element = target as MyButton;
            element.Background = new SolidColorBrush((Color)e.NewValue);
        }
    }

UPDATE:

Чтобы вернуть цвет к значению по умолчанию, просто наберите ClearValue(DependencyProperty) в экземпляре MyButton.

    private void MyButton_Click(object sender, RoutedEventArgs e)
    {
        MyButton myButton = sender as MyButton;
        myButton.ClearValue(MyButton.MyColorProperty);
    }
1 голос
/ 28 февраля 2011

Как насчет этого:

<Window x:Class="WpfApplication3.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication3"
Title="Window2" Height="300" Width="300">
<Window.Resources>

    <Style TargetType="my:MyButton">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=ModeCheckBox, Path=IsChecked}" Value="true">
                <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=MyColor}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=ModeCheckBox, Path=IsChecked}" Value="false">
                <Setter Property="Background" Value="SkyBlue" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <CheckBox Content="Individual Mode" x:Name="ModeCheckBox" Grid.Row="0" />
    <my:MyButton Content="B1" x:Name="myB1" Grid.Row="1" MyColor="Red"/>
    <my:MyButton Content="B2" x:Name="myB2" Grid.Row="2"/>
    <my:MyButton Content="B3" x:Name="myB3" Grid.Row="3" MyColor="Green"/>

</Grid>

</Window>

Я также изменил класс MyButton:

public class MyButton : Button
{
    public Brush MyColor { get; set; }
}
...