繁体   English   中英

WPF组合框绑定占位符项

[英]WPF combobox binding placeholder item

我正在尝试将“假”项目添加到绑定到组合框的源列表中。

<Window ...
        DataContext="{Binding Source={x:Static local:Singleton.Instance}}">
    ...
        <ComboBox ItemsSource="{Binding MyList}">

-

public List<Object> MyList{ get; private set; }

我希望有一个“添加新”作为不属于MyList的组合框项目,因为我只需要在其中包含适当的对象即可。 如果我尝试以编程方式添加它,则会引发异常,因为无法以这种方式编辑源。

将以下内容添加到您的XAML中

IsEditable="True"
Text="Add New"

注意 :如果用户选择绑定值之一,则他们将无法“返回”并选择“添加新”,因为它将不再显示。 同样,既然控件是可编辑的,则在执行任何处理之前,您将需要先验证内容,以避免用户输入错误值而导致的潜在错误。

HappyNomad通过修改Combobox.Templatehttps://stackoverflow.com/a/4053371/5188233中提供了仅xaml的解决方案。 在此建议中,您不需要操纵带有伪造物品的货源清单并保持其清洁。

<ComboBox ItemsSource="{Binding MyList}" ... >
    <ComboBox.Template>
        <ControlTemplate TargetType="ComboBox">
            <Grid>
                <ComboBox x:Name="cbItems" 
                    DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" 
                    ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource TemplatedParent}}"
                    SelectedValue ="{Binding SelectedValue, RelativeSource={RelativeSource TemplatedParent}}" 
                    />
                <TextBlock x:Name="tbItem" Text="Add New" IsHitTestVisible="False" Visibility="Hidden"/>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger SourceName="cbItems" Property="SelectedItem" Value="{x:Null}">
                    <Setter TargetName="tbItem" Property="Visibility" Value="Visible"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </ComboBox.Template>
</ComboBox>

暂无
暂无

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

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