从列表视图动态获取 textBlock

getting textBlock from list view dynamically

我有一个包含 2 个文本块作为列表视图项的 ListView

我想为文本块动态着色

我怎样才能完成文本块? 将欣赏一个例子。

感谢您的支持

附上我的 XAML:

<ListView x:Name="LV" ItemsSource= "{Binding  Lggv}" SelectionChanged="dataGridData_SelectionChanged" ItemContainerStyle="{StaticResource ListViewItemStyle}" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel >
                            <Border BorderThickness="1" BorderBrush="Black">

                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="150"></ColumnDefinition>
                                        <ColumnDefinition Width="50"></ColumnDefinition>
                                        <ColumnDefinition Width="1*"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock x:Name="tbHeader" Text="{Binding Info }" AllowDrop="True"   FontWeight="Bold" Grid.Column="2" >
                                    <TextBlock.Background>
                                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">                                              
                                            <GradientStop Color="#FFCEE6C6" Offset="0.008"/>
                                            <GradientStop Color="#FF9ECF8C" Offset="0.987"/>
                                        </LinearGradientBrush>
                                    </TextBlock.Background>

                                </TextBlock>
                                </Grid>
                            </Border>
                            <Grid x:Name="GridData" >
                                <Grid.Background>
                                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                        <GradientStop Color="#FFC5DDFF" Offset="0"/>
                                        <GradientStop Color="#FFA8C8F7" Offset="1"/>
                                    </LinearGradientBrush>
                                </Grid.Background>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="150"></ColumnDefinition>
                                    <ColumnDefinition Width="50"></ColumnDefinition>
                                    <ColumnDefinition Width="1*"></ColumnDefinition>
                                </Grid.ColumnDefinitions>
                                <Border Grid.Column="0" BorderThickness="2" BorderBrush="Black">
                                    <TextBlock Text="{Binding DateTime}" ></TextBlock>
                                </Border>
                                <Border Grid.Column="1" BorderThickness="2" BorderBrush="Black">
                                    <TextBlock Text="{Binding ComPort}"></TextBlock>
                                </Border>
                                <Border Grid.Column="2" BorderThickness="2" BorderBrush="Black">
                                    <TextBlock Text="{Binding Data}" ></TextBlock>
                                </Border>
                            </Grid>
                        </StackPanel>
                    </DataTemplate>    
                </ListView.ItemTemplate>                                

            </ListView>

如果您使用 MVVM 方法,我会在 ViewModel 中设置颜色并将它们绑定到属性。

编辑: 像这样的文本块:

                               <TextBlock DataContext="ViewModel"
                                       Background="{Binding SpecificColor}">
                               </TextBlock>

并且在 ViewModel 中,您可以在初始化时或在任何特定事件中指定您想要的颜色。 例如:

private Brush m_SpecificColor;
    public Brush SpecificColor
    {
        get { return m_SpecificColor; }
        set
        {
            m_SpecificColor = value;
            OnPropertyChanged("SpecificColor");
        }
    }
    private void SetColor()
    {
        SpecificColor = (Brush)new BrushConverter().ConvertFromString("Green");
    }

我猜您想根据对象的某些 属性 动态更改颜色(class 与 "Info"、"DateTime"、"ComPort" 和 "Data" 属性)在您的 Lggv 源集合中。

然后您可以使用带有绑定到此 class 的 属性 的 DataTrigger 的样式,即 T 类型(这也是具有 [=您绑定到的 IEnumerable<T> (Lggv) 源集合的 17=]、"DateTime"、"ComPort" 和 "Data" 属性:

<TextBlock x:Name="tbHeader" Text="{Binding Info}" AllowDrop="True"   FontWeight="Bold" Grid.Column="2">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Background">
                <Setter.Value>
                    <!-- this is the default background-->
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FFCEE6C6" Offset="0.008"/>
                        <GradientStop Color="#FF9ECF8C" Offset="0.987"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <!-- This trigger changes the background to green when the "Info" property of your data object returns "Some info..." -->
                <DataTrigger Binding="{Binding Info}" Value="Some info...">
                    <Setter Property="Background">
                        <Setter.Value>
                            <SolidColorBrush>Green</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

您可以使用 IValueConverter 将 属性 转换为背景色。下面是一个例子。

class BackgroundColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush();
        if (value != null )
        {
            string strValue = value.ToString();


            myLinearGradientBrush.StartPoint = new System.Windows.Point(0, 0);
            myLinearGradientBrush.EndPoint = new System.Windows.Point(1, 1);

            switch (strValue)
            {
                case "Match1":
                    myLinearGradientBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
                    myLinearGradientBrush.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
                    break;
                case "Match2":
                    myLinearGradientBrush.GradientStops.Add(new GradientStop(Colors.Blue , 0.0));
                    myLinearGradientBrush.GradientStops.Add(new GradientStop(Colors.BlueViolet, 0.25));
                    break;
                default:
                    myLinearGradientBrush.GradientStops.Add(new GradientStop(Colors.Green , 0.0));
                    myLinearGradientBrush.GradientStops.Add(new GradientStop(Colors.GreenYellow, 0.25));
                    break;
            }
        }
        return myLinearGradientBrush;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在资源中声明值转换如下。

<Window.Resources>
    <local:BackgroundColorConverter x:Key="BackgroundColorConverter"/>
 </Window.Resources>

下面是Xaml的coder。

<TextBlock x:Name="tbHeader" Text="{Binding Info }" Background="{Binding Path=property, Converter={StaticResource BackgroundColorConverter}}" AllowDrop="True"   FontWeight="Bold" Grid.Column="2"/>

另一种方法,如果你想使用资源。您可以在 windows 或用户控制资源中定义颜色。在此之后,您将不得不使用 IMultiValueConverter。将 属性 和 windows 或用户控件传递给 MultiValueConverter。您需要使用相对源来获取 windows 或绑定中的用户控件。然后就可以根据匹配条件return资源了。

最好的方法是使用 IValueConverter

因为这允许您将视图和 viewModel 分开,尽管如果您不关心 @sasanaf 的回答是完全正确的

这里是一个简单的基于画笔的转换器的例子

public class PriorityConverter : IValueConverter
{
    public Brush HighBrush { get; set; }
    public Brush LowBrush { get; set; }
    public Brush MediumBrush { get; set; }
    public Brush DefaultBrush { get; set; }
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var priority = value as Priority?;
        if (priority.HasValue)
        {
            switch (priority.Value)
            {
                case Priority.High:
                    return HighBrush;
                case Priority.Medium:
                    return MediumBrush;
                case Priority.Low:
                    return LowBrush;
                default:
                    return DefaultBrush;
            }
        }
        else
            throw new InvalidCastException($"{value} is not a Priority");
    }

然后您可以将转换器作为资源添加到您的应用中,

<local:PriorityConverter x:Key="PriorityConverter" >
    <local:PriorityConverter.DefaultBrush>
        <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.ControlColorKey}}"/>
    </local:PriorityConverter.DefaultBrush>
    <local:PriorityConverter.HighBrush>
        <LinearGradientBrush>
            <GradientStop Color="Red" Offset="0.5"/>
            <GradientStop Color="Yellow" />
        </LinearGradientBrush>
    </local:PriorityConverter.HighBrush>
    <local:PriorityConverter.MediumBrush>
        <SolidColorBrush Color="Blue"/>
    </local:PriorityConverter.MediumBrush>
    <local:PriorityConverter.LowBrush>
        <SolidColorBrush Color="Green"/>
    </local:PriorityConverter.LowBrush>
</local:PriorityConverter>

最后在您的绑定中使用它

<TextBlock Background="{Binding Priority, Converter={StaticResource PriorityConverter}}" />

就我个人而言,我会使用 DataTrigger 执行此操作:

<Style x:Key="TextBlockStyle" TargetType="TextBlock">
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFCEE6C6" Offset="0.008"/>
                <GradientStop Color="#FF9ECF8C" Offset="0.987"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <DataTrigger Binding="{Binding YourProperty}" Value="YourPropertyValue">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Red" Offset="0.008"/>
                        <GradientStop Color="Orange" Offset="0.987"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

然后您不必定义 class 来执行相对简单的任务。