ListBox.SelectedItems未在WPF的样式绑定中刷新

时间:2017-03-17 08:34:27

标签: c# wpf data-binding binding listbox

我正在尝试为我的新工作学习WPF,而我的初始任务是构建一个mutliselect ComboBox。我知道有很多不同的方法,但我试图实现我的自我发展。虽然在这个过程中,我无法成功将ListBox.SelectedItems成功绑定到TextBox。实际上我认为我可以绑定,因为最初会触发Converter,但是当SelectedItems更改时,绑定不会刷新。下面,您可以找到我实现的样式和转换器。是否还有其他技巧可以刷新绑定,或者这种方法根本不可能?

谢谢&问候, ERDI

风格

<Style 
        TargetType="{x:Type ListBox}" 
        x:Key="ComboListBox">
        <Style.Resources>
            <global:VisibilityContentConverter x:Key="VisibilityContentConverter"/>
            <global:ListStringConverter x:Key="ListStringConverter"/>
            <Style TargetType="{x:Type ToggleButton}">
                <Style.Setters>
                    <Setter Property="IsChecked" Value="{Binding ElementName=ItemsList, Path=Visibility, Converter={StaticResource VisibilityContentConverter}}" />
                </Style.Setters>
            </Style>
        </Style.Resources>
        <Style.Setters>
            <Setter Property="Height" Value="100"/>
            <Setter Property="Width" Value="200"/>
            <Setter Property="SelectionMode" Value="Extended"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <StackPanel Orientation="Vertical">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="180"/>
                                    <ColumnDefinition Width="20"/>
                                </Grid.ColumnDefinitions>
                                <TextBox Grid.Column="0" HorizontalAlignment="Stretch" Text="{Binding ElementName=ItemsList, Path=SelectedItems, Converter={StaticResource ListStringConverter}, Mode=OneWay, BindsDirectlyToSource=True}"></TextBox>
                                <ToggleButton Grid.Column="1" Name="Tog" />
                            </Grid>
                            <ListBox ItemsSource="{Binding}" Name="ItemsList" Visibility="Collapsed" SelectionMode="Extended"></ListBox>
                            <Button Content="Erdi"></Button>
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>

转换器

class SelectedItemsToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object     parameter, CultureInfo culture)
        {
            var sb = new StringBuilder();
            foreach (var val in (IList)value)
            {
                sb.Append(val + " ");
            }
            return sb.ToString();
        }

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

0 个答案:

没有答案