WPF Binding to change fill color of ellipse

后端 未结 3 1258
臣服心动
臣服心动 2021-02-13 12:44

How do I programmatically change the color of an ellipse that is defined in XAML based on a variable?

Everything I\'ve read on binding is based on collections and lists

3条回答
  •  感动是毒
    2021-02-13 13:30

    It's worth pointing out that the converter the other posts reference already exists, which is why you can do in xaml in the first place. The converter is System.Windows.Media.BrushConverter:

            BrushConverter bc = new BrushConverter();
            Brush brush = (Brush) bc.ConvertFrom("Red");
    

    The more efficient way is to use the full syntax:

    myEllipse.Fill = new SolidColorBrush(Colors.Red);
    

    EDIT in response to -1 and comments:

    The code above works perfectly fine in code, which is what the original question was asking about. You also don't want an IValueConverter - these are typically used for binding scenarios. A TypeConverter is the right solution here (because you're one-way converting a string to a brush). See this article for details.

    Further edit (having reread Aviad's comment): you don't need to explicitly use the TypeConverter in Xaml - it's used for you. If I write this in Xaml:

    
    

    ... then the runtime automagically uses a BrushConverter to turn the string literal into a brush. That Xaml is essentially converted into the equivalent longhand:

    
      
         
                   
    
    

    So you're right - you can't use it in Xaml - but you don't need to.

    Even if you had a string value that you wanted to bind in as the fill, you don't need to specify the converter manually. This test from Kaxaml:

    
      
        Red
      
    
        
        
      
    
    

    Strangely, you can't just use the StaticResource col and still have this work - but with the binding it and automatically uses the ValueConverter to turn the string into a brush.

提交回复
热议问题