1

我有一个绑定到用户对象集合的组合框。组合的 DisplayMemberPath 设置为“名称”,这是用户对象的属性。我还有一个文本框,它绑定到 ComboBox.SelectedItem 绑定的同一个对象。因此,当我更改 TextBox 中的文本时,我的更改会立即反映在组合中。只要 Name 属性未设置为空白,这正是我想要发生的。在这种情况下,我想替换一段通用文本,例如“{请提供姓名}”。不幸的是,我不知道该怎么做,所以在这方面的任何帮助将不胜感激!

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow"
    Width="340"
    SizeToContent="Height"
    WindowStartupLocation="CenterScreen"
    ResizeMode="NoResize">
<StackPanel>
    <TextBlock Text="ComboBox:" />
    <ComboBox SelectedItem="{Binding SelectedUser}"
              DisplayMemberPath="Name"
              ItemsSource="{Binding Users}" />
    <TextBlock Text="TextBox:"
               Margin="0,8,0,0" />
    <TextBox Text="{Binding SelectedUser.Name, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

public class ViewModel : INotifyPropertyChanged
{
    private List<User> users;
    private User selectedUser;

    public event PropertyChangedEventHandler PropertyChanged;

    public List<User> Users
    {
        get
        {
            return users;
        }
        set
        {
            if (users == value)
                return;

            users = value;

            RaisePropertyChanged("Users");
        }
    }

    public User SelectedUser
    {
        get
        {
            return selectedUser;
        }
        set
        {
            if (selectedUser == value)
                return;

            selectedUser = value;

            RaisePropertyChanged("SelectedUser");
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;

        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class User
{
    public string Name { get; set; }
}
4

2 回答 2

1

看看这个post。有几个答案可能满足您的要求。

于 2013-03-15T21:11:06.590 回答
0

您可以使用 TargetNullValue

<StackPanel>
    <TextBlock Text="ComboBox:" />
    <ComboBox SelectedItem="{Binding SelectedUser}" ItemsSource="{Binding Users}" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock 
                    Text="{Binding Name, TargetNullValue='Enter some text'}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    <TextBlock Text="TextBox:"
        Margin="0,8,0,0" />
    <TextBox Text=
             "{Binding SelectedUser.Name, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

并将空名称转换为 null。

public class User 
{
    private string name;

    public string Name
    {
        get
        {
            return this.name;
        }
        set
        {
            this.name = (string.IsNullOrEmpty(value)) ? null : value;

            // probably best raise property changed here
        }
    }
}
于 2013-03-15T21:25:29.493 回答