WPF TextBox中的ListBox - 芯片

时间:2016-08-23 11:15:03

标签: wpf xaml listbox wpf-controls custom-controls

我需要在TextBox中添加ListBox,即CHIPS

参考屏幕截图:( 期望

enter image description here

只考虑视图模型:

public class Person
{
    private ObservableCollection<string> _personList = new ObservableCollection<string>();

    public ObservableCollection<string> PersonList
        {
            get { return _personList; }
            set
            {
                _personList = value;
                if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("PersonList"));
            }
        }

    private string _personStr = String.Empty;

    public string PersonStr
        {
            get { return _personStr; }
            set
            {
                _personStr = value;
                if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("PersonStr"));
            }
        }

    public Person()
        {
            PersonList.Add("IR-Punch");
            PersonList.Add("Stack-Overflow");
        }

    public ICommand BTextCommand
        {
            get
            {
                return new DelegateCommand(AppendString);
            }
        }

    public void AppendString()
        {
            PersonList.Add(PersonStr);
        }
}

正在运行的XAML源代码:

<ItemsControl ItemsSource="{Binding PersonList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding }" TextWrapping="Wrap"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

<TextBox Text="{Binding PersonStr}" Width="160" VerticalAlignment="Center" />

<Button Command="{Binding BTextCommand}" Content="Add" />

请帮助我如何在ListBox中添加TextBox。我照顾Sytle。我期待着核心理念。

1 个答案:

答案 0 :(得分:1)

不要尝试在TextBox中嵌入其他控件,而是将ItemsControl和TextBox嵌入到堆栈面板中,如下所示:

<Border BorderThickness="1">
    <ScrollViewer VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto">
        <StackPanel Orientation="Horizontal">
            <ItemsControl ItemsSource="{Binding PersonList}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
            <TextBox MinWidth="100" BorderBrush="Transparent" BorderThickness="0" Text="{Binding PersonStr}" />
        </StackPanel>
    </ScrollViewer>
</Border>

您需要将外边框的样式设置为TextBox(几乎只是找到正确的BorderBrush),但是,根据要求,我已经将样式留给了您。

请注意,我实际上没有尝试过这个解决方案,只是把它作为一种应该有用的方法。如果您有任何问题,请告诉我。