首页 文章

WPF / XAML:基于自定义属性切换样式

提问于
浏览
2

我有一个带有以下xaml的WPF用户控件

<UserControl x:Class="Scheduler.ItemBox"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="40" d:DesignWidth="150" MinHeight="40" MinWidth="75" VerticalAlignment="Top">
 <Border BorderBrush="CornflowerBlue" BorderThickness="1" CornerRadius="5" Name="border">
     <Border.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="White" Offset="0"/>
            <GradientStop Color="#FFC0D3EA" Offset="1"/>
        </LinearGradientBrush>
    </Border.Background>
    <Grid Margin="2,0" Name="grid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20" MaxHeight="20" MinHeight="20" />
            <RowDefinition MinHeight="20" />
        </Grid.RowDefinitions>
        <Label Content="00:00" FontWeight="Bold" Name="FromTime" Padding="5,0,0,0" VerticalContentAlignment="Center" />
        <Label Content="01:30" Grid.Column="1" HorizontalContentAlignment="Right" Name="ToTime" Padding="0,0,5,0" VerticalContentAlignment="Center" />
        <TextBlock Grid.ColumnSpan="2" Grid.Row="1" Name="MovieTitle" Padding="5,0" Text="item1" TextWrapping="Wrap" />
    </Grid>
</Border>

用户控件类看起来像这样

Namespace Scheduler
Public Class ItemBox

    Public Property Selected As Boolean

End Class

结束命名空间

现在我想要做的是,当我将属性更改为True时,将以下内容: - 将border borderbrush设置为黑色 - 将border borderthickness设置为2 - 将grid margin设置为1

我想通过在usercontrol中定义一个“selected”样式来实现这一点,该样式在selected属性设置为True时覆盖默认样式 .

我知道它与样式触发器和定义自定义附加属性有关 . 但我似乎无法按照我想要的方式工作 .

1 回答

  • 0

    第一个问题是您的Selected属性不是“可观察的” . 这意味着任何正在观察属性以进行更改的内容(例如样式触发器或绑定)都不会被通知它已更改 .

    您可能需要实现INotifyPropertyChanged或将您的属性设为Dependency Property . 它不需要是附加属性,因为如果需要,可以使用RelativeSource绑定到属性 .

    第二个问题是你的UserControl没有Style,至少在默认情况下不是 . 即使您设置了UserControl.Style属性,也无法轻松更改内容 . 这是使用custom Control更容易完成的事情,并且是您完成所需内容的最佳选择 .

相关问题