Silverlight -动态改变按钮文本的颜色

本文关键字:文本 颜色 按钮 改变 动态 Silverlight | 更新日期: 2023-09-27 17:53:27

我正在尝试使用ViewModel改变Silverlight表单上动态创建按钮的按钮文本颜色。我面临的问题是,当我改变按钮文本的颜色时,所有按钮都会受到影响。由于按钮是动态创建的,因此我无法对其进行控制。

有人建议我写一个ForegroundColor属性到模型,然后附加到按钮,我尝试了你在代码中看到的,但不能做太多关于它。

你能看到我在做什么,并帮助我与你的建议,因为我不确定,我正在做正确的方式。

感谢

namespace Web.Models
{
  [DataContract(IsReference = true)]
  public class Sales
  {
    [DataMember]
    public int SalesId { get; set; }
    [DataMember]
    public int ShowOrder { get; set; }
    [DataMember]
    public bool Active { get; set; }
    [DataMember]
    public bool Regurgitate { get; set; }
    [DataMember]
    public int ForegroundColor { get; set; }
    public Sales(Salese result)
    {
        SalesId = result.SalesId;
        ShowOrder = result.ShowOrder;
        Active = result.Active;
        Regurgitate = result.Regurgitate;            
        if (SalesId == 12)
        {
            var bytes = System.BitConverter.GetBytes(ForegroundColor);
            Color btnColor = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
            SolidColorBrush myBrush = new SolidColorBrush(btnColor);
        }
   }
}

}

ViewModel

private Brush _foregroundColor = new SolidColorBrush(Colors.Black); 
public override void Loaded()
{
    OnMainOutcome();
}

public Brush ForegroundColor
{
   get { return _foregroundColor; }
   set
   {
       if (_foregroundColor == value) return;
       _foregroundColor = value;                
       OnPropertyChanged("ForegroundColor");
    }
 }
 private void OnMainOutcome()
 {
    var selectedSalesId = (int)OutcomeCommand.CommandParameter;
    CurrentSubOutcomes = GetCurrentSubOutcomes(selectedSalesId);
    foreach (var index in CurrentOutcomes)
    {
       if (index.OutcomeId == 12)        
          ForegroundColor = new SolidColorBrush(Colors.Red);
       else
          ForegroundColor = new SolidColorBrush(Colors.Black);
    }
 }

XAML编辑

 <controls:ChildWindow.Resources>
    <converters:NumericToColorConverter x:Key="NumericToColorConverter"/>
</controls:ChildWindow.Resources>
 <ListBox Grid.Row="1" Height="Auto" MinHeight="200" Width="160" Margin="2,2,2,2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding Path=CurrentOutcomes}" Background="{x:Null}" BorderBrush="{x:Null}">
      <ListBox.ItemTemplate>
          <DataTemplate>
               <Button Height="30" Width="150" HorizontalAlignment="Center" Content="{Binding Outcome}" CommandParameter="{Binding SalesOutcomeId }" Command="{Binding Source={StaticResource ViewModel}, Path=OutcomeCommand}" Foreground="{Binding Source={StaticResource ViewModel}, Converter={StaticResource NumericToColorConverter}, Path=ForegroundColor}" />
          </DataTemplate>
      </ListBox.ItemTemplate>
 </ListBox>

转换类NEW

  using System;
  using System.Windows.Data;
  using System.Windows.Media;
  using System.Windows;
  namespace Converters
  {
      public class NumericToColorConverter : IValueConverter
      {
        static readonly SolidColorBrush RED_BRUSH = new SolidColorBrush(Colors.Red);
        static readonly SolidColorBrush BLUE_BRUSH = new SolidColorBrush(Colors.Blue);
        public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
        {
           //Int32 id = System.Convert.ToInt32(value);
           //LinearGradientBrush brush = new LinearGradientBrush();
           //brush.StartPoint = new Point(0, 1);
           //brush.EndPoint = new Point(0, 0);
           //brush.GradientStops.Add(new GradientStop()
           //{
           //    Color = Colors.White,
           //    Offset = 0
           //});
           //brush.GradientStops.Add(new GradientStop()
           //{            
           //    Color = Color.FromArgb(
           //        200,
           //        System.Convert.ToByte((id * 103) % 256),
           //        System.Convert.ToByte((id * 157) % 256),
           //        System.Convert.ToByte((id * 233) % 256)
           //    ),
           //    Offset = 1
           //});
           //return brush;
           var OutcomeId = (int)value;
           if (OutcomeId == 12)
           {
              return RED_BRUSH;
           }
           else
           {
              return BLUE_BRUSH;
           }
    }
    public object ConvertBack(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

}

Silverlight -动态改变按钮文本的颜色

您将Foreground绑定到StaticResource上的值,因此所有按钮都将绑定到相同的值。

你可以创建一个特定的"ButtonForegroundConverter",或者你可以添加画笔属性到项目级视图模型,也有Outcome属性,你已经绑定到按钮的Content。然后按钮xaml看起来像这样:

<Button ...
        Content="{Binding Outcome}" 
        Foreground="{Binding OutcomeForegroundBrush}" 
        ...
        />

如果你直接绑定到一个实体,那么像那样添加属性不是一个好主意,所以上面的例子假设你有一个中间视图模型或控制器,你可以在上面添加这样的属性。

如果您选择使用转换器,它将看起来像这样:

<Button ...
        Content="{Binding Outcome}" 
        Foreground="{Binding OutcomeId, Converter={StaticResource OutcomeToForegroundConverter}}" 
        ...
        />

和转换器:

namespace MyConverters {
    public sealed class OutcomeToColorConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            // We must have a valid integer value, double check bindings
            if (value == null) {
                throw new ArgumentNullException("value", 
                    "Please make sure the value is not null.");
            }
            var OutcomeId = (int)value;
            if (OutcomeId == XXX) { 
                return RED_BRUSH; 
            }
            else {
                return BLUE_BRUSH;
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
        static readonly SolidColorBrush RED_BRUSH = new SolidColorBrush(Colors.Red);
        static readonly SolidColorBrush BLUE_BRUSH = new SolidColorBrush(Colors.Blue);
    }
}

记住声明资源:

<myconverters:OutcomeToForegroundConverter x:Key="OutcomeToForegroundConverter" />

您的列表框显示了Sales的列表,但是每个项目都是模板化的,以便将按钮前景绑定到VM中的单个属性。在Sales类中创建MyBrush属性并绑定到它。

namespace Web.Models
{
  [DataContract(IsReference = true)]
  public class Sales
  {
    [DataMember]
    public int SalesId { get; set; }
    [DataMember]
    public int ShowOrder { get; set; }
    [DataMember]
    public bool Active { get; set; }
    [DataMember]
    public bool Regurgitate { get; set; }
    [DataMember]
    public int ForegroundColor { get; set; }
    [DataMember]
    public SolidColorBrush MyBrush { get; set; }
    public Sales(Salese result)
    {
        SalesId = result.SalesId;
        ShowOrder = result.ShowOrder;
        Active = result.Active;
        Regurgitate = result.Regurgitate;            
        if (SalesId == 12)
        {
            var bytes = System.BitConverter.GetBytes(ForegroundColor);
            Color btnColor = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
            MyBrush = new SolidColorBrush(btnColor);
        }
   }
}

<ListBox Grid.Row="1" Height="Auto" MinHeight="200" Width="160" Margin="2,2,2,2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding Path=CurrentOutcomes}" Background="{x:Null}" BorderBrush="{x:Null}">
      <ListBox.ItemTemplate>
          <DataTemplate>
               <Button Height="30" Width="150" HorizontalAlignment="Center" Content="{Binding Outcome}" CommandParameter="{Binding SalesOutcomeId }" Command="{Binding Source={StaticResource ViewModel}, Path=OutcomeCommand}" Foreground="{Binding MyBrush}"  />
          </DataTemplate>
      </ListBox.ItemTemplate>
 </ListBox>