ItemsControl在运行时修改Items

时间:2011-12-02 13:45:57

标签: wpf silverlight xaml

在我的Silverlight项目中,我有以下ItemsControl:

<ItemsControl x:Name="ItemsList">
    <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
    <DataTemplate>

        <Border x:Name="brdItem" Opacity="1" MouseLeftButtonDown="brdItem_MouseLeftButtonDown">
            <TextBlock x:Name="txtUsername" Text="{Binding Username}" />
        </Border>

    </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

我想要的是: 当我的用户点击某个项目时。我希望所有其他项目Opacity设置为“0.3”。 释放鼠标时,我希望所有项目都恢复到原始状态(Opacity =“1”)。

1 个答案:

答案 0 :(得分:2)

如果使用MVVM模式,则非常简单。将Opacity属性添加到item类并将其绑定到Border.Opacity属性:

<Border x:Name="brdItem" Opacity="{Binding Opacity}" MouseLeftButtonDown="brdItem_MouseLeftButtonDown">
    <TextBlock x:Name="txtUsername" Text="{Binding Username}" />
</Border>

项目类:

public class ItemViewModel : INotifyPropertyChanged
{
    public string Username { get; set; }

    private double _opacity;

    public double Opacity
    {
        get { return _opacity; }
        set
        {
            _opacity = value;
            RaisePropertyChanged("Opacity");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

之后,您的鼠标事件将如此:

    public void brdItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var vm = ((FrameworkElement)sender).DataContext as ItemViewModel;
        if (vm != null)
        {
            vm.Opacity = 1;
            this.ItemsList.ItemsSource.OfType<ItemViewModel>()
                .Where(item => item != vm)
                .ToList()
                .ForEach(item => item.Opacity = 0.3);
        }
    }

要返回初始状态,请使用以下代码:

this.ItemsList.ItemsSource.OfType<ItemViewModel>()
    .ToList().ForEach(item => item.Opacity = 1);