如何在用户控件中动态设置元素的样式

时间:2017-02-24 20:42:05

标签: wpf binding user-controls

在WPF项目中,我有一个定义多边形形状的用户控件(Valve.xaml)。

<Grid>
   <Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Open}"/>
</Grid>

我在窗口xaml(FFG.xaml)文件中显示Valve用户控件,如下所示:

<Window
   <!-- removed other namespaces for brevity -->
   xmlns:cl="clr-namespace:FFG.Controls;assembly=PID.Controls">
   <Grid>
      <cl:Valve x:Name="valve201A"></cl:Valve>
   </Grid>
</Window>

我将FFG.xaml的DataContext设置为类FFG_ViewModel.cs,它包含Valve_Model类的实例。 Valve_Model实质上代表在FFG.xaml窗口上绘制的阀门。

public class FFG_ViewModel : ViewModelBase {

   public Valve_Model Valve201A { get; set; }

   // There are other properties and methods, but I've removed them for brevity also

}

这是Valve_Model类:

public class Valve_Model  INotifyPropertyChanged {

        public event PropertyChangedEventHandler PropertyChanged;

        private bool _isValveOpen { get; set; }
        public bool IsValveOpen {
            get {
                return _isValveOpen;
            }
            set {
                _isValveOpen = value;
                OnPropertyChanged("IsValveOpen");
            }
        }

        #region INotifyPropertyChanged
        protected virtual void OnPropertyChanged(string propertyName) {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null) {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }
        #endregion

    }

问题: 我想要的是Valve.xaml中的Style属性在IsValveOpen属性更改时更改。

因此,如果阀门打开,那么它将是:

<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Open}"/>

当属性更改为false时,我需要将多边形的样式更改为:

<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Closed}"/>

我如何准确地实现这一目标?

3 个答案:

答案 0 :(得分:1)

您可以使用IMultiValueConverter

首先,让我们简化用例。基本上,您希望基于给定的状态对象交换Styles,我将用ToggleButton表示。你在UserControl中包装所有内容的事实也对基本概念没有影响。

演示:

  • 开始一个新项目
  • 声明我们的Resources
  • Window和州提供给Converter

<强> MainWindow.xaml

<Window 

    ...

    >
    <Window.Resources>
        <local:ToStyleConverter x:Key="ToStyleConverter"/>
        <Style x:Key="Valve_Open" TargetType="{x:Type Polygon}">
            <Setter Property="Fill" Value="Red"/>
        </Style>
        <Style x:Key="Valve_Closed" TargetType="{x:Type Polygon}">
            <Setter Property="Fill" Value="Green"/>
        </Style>
    </Window.Resources>
    <DockPanel>
        <ToggleButton x:Name="butt" DockPanel.Dock="Bottom">Switch</ToggleButton>
        <Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Stretch="Uniform">
            <Polygon.Style>
                <MultiBinding Converter="{StaticResource ToStyleConverter}">
                    <Binding RelativeSource="{RelativeSource FindAncestor, 
                                              AncestorType={x:Type Window}}"/>
                    <Binding ElementName="butt" Path="IsChecked"/>
                </MultiBinding>
            </Polygon.Style>
        </Polygon>
    </DockPanel>
</Window>

<强> MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

public class ToStyleConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, 
        object parameter, System.Globalization.CultureInfo culture)
    {
        if (values[0] is Window)
        {
            Window win = (Window)values[0];
            if ((bool)values[1])
                return win.FindResource("Valve_Open");
            if (!(bool)values[1])
                return win.FindResource("Valve_Closed");
        }
        return DependencyProperty.UnsetValue;
    }

    public object[] ConvertBack(object values, Type[] targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

更改为任何特定用例意味着:

  • 将relativesource绑定指向包含Control(样式)的Resources
  • 使用第二个绑定将状态添加到Converter(DP / INPC)
  • 实施Converter逻辑

答案 1 :(得分:0)

您可以(应该尽我所能)在DataTrigger内使用ControlTemplate。假设这两个是你的样式:

<Window.Resources>
    <Style TargetType="Polygon" x:Key="Valve_Open">
        <Setter Property="Fill" Value="Red"/>
    </Style>
    <Style TargetType="Polygon" x:Key="Valve_Close">
        <Setter Property="Fill" Value="Green"/>
    </Style>
</Window.Resources>

您应该将此样式添加到资源中:

 <Style x:Key="changeStyle" TargetType="Control">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Control">
                    <Grid>
                        <Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Open}" />
                    </Grid>
                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding Valve201A.IsValveOpen}" Value="true">
                            <Setter TargetName="pValve" Property="Style" Value="{StaticResource Valve_Close}" />
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

并在您的观看中使用它们:

 <Control DataContext="{Binding}" Style="{StaticResource changeStyle}" />

答案 2 :(得分:0)

您可以向Style本身添加Style,而不是将实际的DataTrigger属性设置为新值,而是根据{的值更改Polygon的属性{1}}来源属性。

<强> Valve.xaml:

IsValveOpen

<强> FFG.xaml:

<Grid>
    <Polygon Name="pValve" Points="0,50 0,20 50,50 50,20">
        <Polygon.Style>
            <Style TargetType="Polygon">
                <!-- Copy the setters from the Valve_Closed style here -->
                <Setter Property="Fill" Value="Red" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsValveOpen}" Value="True">
                        <!-- Copy the setters from the Valve_Open style here -->
                        <Setter Property="Fill" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Polygon.Style>
    </Polygon>
</Grid>