将列表框中选定的项目信息传递给用户控件(WPF)

3
我有一个列表框,每个列表框项是我创建的自定义用户控件。我使用样式来删除列表框项的所有默认高亮(即删除所选项目的蓝色背景高亮)。
我想要对我的用户控件进行特殊处理,以表示列表框项已突出显示。例如,使用户控件上的边框更加粗体等。
如果我可以将布尔值传递到用户控件中,我认为我将能够通过转换器或类似的方式弄清楚如何对用户控件进行必要的更改。
我不确定的是,我该如何将显示用户控件所在的列表框项是否被突出显示的信息传递到用户控件中。
相关代码如下:
<ListBox.ItemTemplate>
 <DataTemplate>
  <hei:OrangeUserCtrl DataContext="{Binding}" Height="40" Width="40" />
 </DataTemplate>
</ListBox.ItemTemplate>

如何将列表框中的项目突出显示传递给用户控件(最好作为true/false)?

谢谢。

2个回答

1
你可以使用Tag属性和RelativeSource绑定。
在我的例子中,当项目被突出显示时,我改变了边框属性(BorderBrush=RedBorderThickness=3)。
源代码:
简单的类来保存数据:
class Person
{
   public string Name { get; set; }
   public string Surname { get; set; }
}

列表框:

 <ListBox ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <local:MyCustomPresenter DataContext="{Binding}" 
                                             Tag="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, UpdateSourceTrigger=PropertyChanged}"
                                             Height="60" Width="120" />               
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>   

用于显示自定义数据的用户控件:

<UserControl x:Class="WpfTextWrapping.MyCustomPresenter"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Border Margin="10">
        <Border.Style>
            <Style TargetType="Border">
                <Setter Property="BorderBrush" Value="Green" />
                <Setter Property="BorderThickness" Value="1" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, UpdateSourceTrigger=PropertyChanged}" Value="True">
                        <Setter Property="BorderBrush" Value="Red" />
                        <Setter Property="BorderThickness" Value="3" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Border.Style>

        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Name}" />
            <TextBlock Text="{Binding Surname}" />
        </StackPanel>        
    </Border>
</UserControl>

0

如果我理解得正确,您需要向自定义的UserControl添加一个属性,该属性绑定到嵌套的ComboBox,类似于:

  public object MySelectedItem
    {
        get { return myNestedCombox.SelectedItem; }
        set { myNestedCombox.SelectedItem = value; }
    }

你还需要进行NotifyPropertyChanged操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接