繁体   English   中英

ListBox绑定到ObservableCollection <string>

[英]ListBox binding to ObservableCollection<string>

在下面的类中,列表框的itemssource应该绑定到Interfaces属性。

public class BaseClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private const string TYPE_TITLE = "Type";

    private string  _Type;

    public string Type
    {
        get { return _Type; }
        set { _Type = value; this.NotifyPropertyChanged(PropertyChanged, TYPE_TITLE); }
    }

    public ObservableCollection<string> Interfaces { get; set; }

    public BaseClass()
    {
        Interfaces = new ObservableCollection<string>();
    }

    public void Reset()
    {
        _Type = null;
        Interfaces.Clear();
    }
}

在该列表框中,所选项目应能够作为内联编辑方案进行编辑,

<DataTemplate x:Key="BaseClass_Interfaces_InlineEdit_Template">
    <TextBox Text="{Binding Mode=TwoWay, Path=., NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}" TextChanged="TextBox_TextChanged"/>
</DataTemplate>
<DataTemplate x:Key="BaseClass_Interfaces_InlineView_Template">
    <TextBlock Text="{Binding Path=., UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>

<Style TargetType="{x:Type ListBoxItem}" x:Key="BaseClass_Iterfaces_ItemStyle_Template">
    <Setter Property="ContentTemplate" Value="{StaticResource BaseClass_Interfaces_InlineView_Template}" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource BaseClass_Interfaces_InlineEdit_Template}" />
        </Trigger>
    </Style.Triggers>
</Style>

ListBox有一个作为父层次结构的容器,其DataContext属性绑定到BaseClass实例,因此ListBox可以绑定到Interfaces属性。

<ListBox Grid.Row="2" Grid.ColumnSpan="2" Margin="3" ItemsSource="{Binding Interfaces, Mode=TwoWay}" SelectionMode="Single"
             ItemContainerStyle="{StaticResource ResourceKey=BaseClass_Iterfaces_ItemStyle_Template}" />
  • 选择任何项目之前的列表框
    选择任何项目之前的列表框
  • 编辑所选项目
    编辑所选项目
  • 编辑后选择另一个项目,更改不会受到影响
    编辑后选择已更改

有两个问题:

  1. TextBox应该具有“ Path =”。 否则,“双向绑定需要Path或XPath”。 收到异常消息。
  2. 考虑到上述问题,文本更改后,ObservableCollection项将永远不会更新!

我找到了答案!
我想知道文本框的文本属性已更改,但更改未传播到源,基于链接的绑定机制将对源属性起作用,换句话说,属性的更改将监视对象本身。
解决方案是围绕字符串的包装器类,我之前为另一种原始类型(布尔型)编写了该包装器。

public class Wrapper<T>
{
    public T Item { get; set; }

    public Wrapper(T value = default(T))
    {
        Item = value;
    }

    public static implicit operator Wrapper<T>(T item)
    {
        return new Wrapper<T>(item);
    }

    public static implicit operator T(Wrapper<T> item)
    {
        if (null != item)
            return item.Item;

        return default(T);
    }
}

因此,编辑数据模板的变化如下

<DataTemplate x:Key="BaseClass_Interfaces_InlineEdit_Template">
    <TextBox Text="{Binding Mode=TwoWay, Path=Item, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>  

每件事都是魅力!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM