Silverlight - 动态创建的更改按钮文本颜色

时间:2013-01-16 10:04:01

标签: c# silverlight xaml

我正在尝试使用ViewModel更改Silverlight表单上动态创建的按钮的按钮文本颜色。我面临的问题是,当我更改按钮文本的颜色时,所有按钮都会生效。由于按钮是动态创建的,我无法控制它。

我被建议将一个ForegroundColor属性写入Model,然后附加到按钮,我在代码中看到了,但是对它没有多大帮助。

你能看到我在做什么,并帮助我提出你的建议,因为我不确定,我正在这样做。

由于

模型

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);
        }
   }
}

}

视图模型

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>

转换器类新

  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();
    }
}

}

2 个答案:

答案 0 :(得分:1)

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

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>

答案 1 :(得分:1)

Foreground绑定到StaticResource上的值,以便所有按钮都绑定到同一个值。

您可以创建特定的“ButtonForegroundConverter”,也可以将Brush属性添加到项目级别视图模型中,该视图模型还具有已绑定到按钮的Outcome的{​​{1}}属性。然后按钮xaml将如下所示:

Content

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

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

<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);
    }
}