简体   繁体   中英

Change style based on property value

On a Canvas of the main window I'm drawing some sensors.

I created the class "Sensor"

public class Sensor
{
    public int Id_Sens { get; set; }    
    public int Type { get; set; }
    public UIElement Ui_Element { get; set; }
}

Programmatically I create a Grid with two columns (a Rectangle with the same WIDTH and HEIGHT (-> become a square), with the following Style, in the first one and a Label in the second). I associate this Grid with the Ui_Element ( Ui_Element = gridMain ).

This works fine.

Based on the value of the property Type , I want to change the radius of the Rectangle (and draw a circle)

I created the follow XAML

<Style x:Key="Sens_Shape" TargetType="{x:Type Rectangle}">
    <Setter Property="Stroke" Value="Black"/>
    <Setter Property="StrokeThickness" Value="1"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Type}" Value="0">
            <Setter Property="RadiusX" Value="60"/>
            <Setter Property="RadiusY" Value="60"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

How do I bind the property Type of the class Sensor to the trigger?

EDIT I solved with the points 1 and 3 of of EldHasp

I may not give an exact answer, because there are not enough details in the original question.

  1. The element that you show in the Window is recorded in the property public UIElement Ui_Element ?
    If so, then change the property type to public FrameworkElement Ui_Element , since the Style and DataContext properties are defined on the FrameworkElement, not UIElement.

  2. If it is a narrower type (for example, it is always Shape as in your examples), then it is even better to specify this narrower type.

  3. If the style shown by you is the style of the element in the Ui_Element property, then it is enough to pass the Sensor into the Data Context of this element.
    Example: sensor.Ui_Element.DataContext = sensor; .

  4. You are very vainly creating UI elements on Sharpe. The core language of WPF is XAML. And in very rare, rather difficult cases, it is worth using Sharp instead. In most cases, a XAML solution will be more simpler, more typical, more understandable than Sharpe.
    In your case, you should create a Sensor's collection without the Ui_Element property. Create a template selector for the Sensor which, by the Type property, will set its visual appearance. In XAML, set the ItemsControl for this collection and give it a template selector.
    Besides there are several other typical WPF implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM