绑定属性以针对每个项单独更改列表框项前景

时间:2011-11-18 21:30:40

标签: c# wpf data-binding mvvm listbox

我正在尝试为每个项目单独更改ListBox中项目的前景色,我已经发布了类似的问题,但这个问题更具体。

我希望为添加到ListBox的每个项目保留颜色的状态,所以我尝试创建一个属性(在本例中为“HotkeysForeground”),绑定它并在项目添加到项目中时更改颜色“HotkeyManager_NewHotkey”事件,它正在改变ListBox中所有项目的前景色。

我如何按项目执行此操作?

这是我使用的ViewModel。

namespace Monkey.Core.ViewModel
{
    using System;
    using System.Collections.ObjectModel;
    using System.Windows.Media;

    using Monkey.Core.SystemMonitor.Accessibility;
    using Monkey.Core.SystemMonitor.Input;

    public class MainWindowViewModel : WorkspaceViewModel
    {
        private readonly FocusManager _focusManager;

        private readonly HotkeyManager _hotkeyManager;

        private readonly ObservableCollection<string> _hotkeys;

        private Color _foregroundColor;

        private string _title;

        public MainWindowViewModel()
        {
            _hotkeys = new ObservableCollection<string>();

            _hotkeyManager = new HotkeyManager();
            _hotkeyManager.NewHotkey += HotkeyManager_NewHotkey;

            _focusManager = new FocusManager();
            _focusManager.Focus += FocusManager_Focus;
        }

        public Color HotkeysForeground
        {
            get
            {
                return _foregroundColor;
            }
            set
            {
                _foregroundColor = value;

                OnPropertyChanged(() => HotkeysForeground);
            }
        }

        public ReadOnlyObservableCollection<string> Hotkeys
        {
            get
            {
                return new ReadOnlyObservableCollection<string>(_hotkeys);
            }
        }

        public string Title
        {
            get
            {
                return _title;
            }
            set
            {
                _title = value;

                OnPropertyChanged(() => Title);
            }
        }

        protected override void OnDispose()
        {
            base.OnDispose();

            _hotkeyManager.Dispose();

            _focusManager.Dispose();
        }

        private void FocusManager_Focus(object sender, FocusManagerEventArgs e)
        {
            Title = e.Title;
        }

        private void HotkeyManager_NewHotkey(object sender, EventArgs eventArgs)
        {
            HotkeysForeground = _hotkeys.Count <= 2 ? Colors.Blue : Colors.Brown;

            _hotkeys.Clear();

            foreach (var hotkey in _hotkeyManager.GetHotkeys())
            {
                _hotkeys.Add(hotkey);
            }
        }
    }
}

以下是观点。

<Window x:Class="Monkey.View.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="{Binding Mode=OneWay, Path=Title, UpdateSourceTrigger=PropertyChanged}" Height="200" Width="200" ShowInTaskbar="False" WindowStyle="ToolWindow" Topmost="True" ResizeMode="CanResizeWithGrip" AllowsTransparency="False">
    <Window.Resources>
        <SolidColorBrush Color="{Binding HotkeysForeground}" x:Key="HotkeysBrush"/>
    </Window.Resources>
    <ListBox 
        Canvas.Left="110" 
        Canvas.Top="74" 
        Name="HotkeyList" 
        Height="Auto" Width="Auto" HorizontalContentAlignment="Left" 
        BorderThickness="0"
        ScrollViewer.CanContentScroll="False"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        ScrollViewer.VerticalScrollBarVisibility="Disabled"
        ItemsSource="{Binding Path=Hotkeys}" VerticalAlignment="Stretch" VerticalContentAlignment="Center" FontSize="20">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="IsEnabled" Value="False" />
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding}" Foreground="{StaticResource HotkeysBrush}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

提前谢谢。

1 个答案:

答案 0 :(得分:1)

对我来说听起来很糟糕。如果您有比热键字符串更多的数据,只需创建一个类并将颜色与显示字符串一起存储为单独的属性。

修改:示例:

public class HotkeyViewModel
{
    private readonly string _DisplayString;
    public string DisplayString { get { return _DisplayString; } }

    private readonly Color _Color;
    public Color Color { get { return _Color; } }

    public HotkeyViewModel(string displayString, Color color)
    {
        _DisplayString = displayString;
        _Color = color;
    }
}

您还可以对属性进行修改,但如果有任何绑定需要更新,则需要implement INPC

新集合的类型应为ObservableCollection<HotkeyViewModel>,模板有两个绑定:

<DataTemplate>
    <Label Content="{Binding DisplayString}">
        <Label.Background>
            <SolidColorBrush Color="{Binding Color}" />
        </Label.Background>
    </Label>
</DataTemplate>

(您还可以将该属性设为Brush并直接绑定到Background