如何避免文本框中的默认文本?

时间:2011-01-25 04:28:54

标签: wpf mvvm string-formatting multibinding

我有一个文本框,它使用多绑定usingStringFormat ...,如下所示。 但它显示默认值为 {DependencyProperty.UnsetValue},{DependencyProperty.UnsetValue}

如何避免这种情况?

<StackPanel Orientation="Horizontal">
                    <TextBlock Width="70" Text="Name:" Margin="5,2,2,2"></TextBlock>
                    <TextBox Width="160" DataContext="{Binding }" IsReadOnly="True" Margin="2">
                        <TextBox.Text>
                            <MultiBinding StringFormat="{}{0},{1}">
                                <Binding Path="LastName"/>
                                <Binding Path="FirstName"/>
                            </MultiBinding>
                        </TextBox.Text>
                    </TextBox>
</StackPanel>

请帮帮我。

2 个答案:

答案 0 :(得分:0)

只需给出fallbackvalue =“”并查看

<TextBox.Text>
                <MultiBinding StringFormat="{}{0},{1}">
                    <Binding Path="LastName" FallbackValue=""/>
                    <Binding Path="FirstName" FallbackValue=""/>
                </MultiBinding>
            </TextBox.Text>

如果绑定不成功,即未找到绑定源的路径或值转换器(如果有)失败,则返回DependencyProperty.UnsetValue,然后将target属性设置为FallbackValue(如果已定义)当然是其中之一。

答案 1 :(得分:0)

您要绑定的对象有问题。我刚刚从头创建了一个带有继承自DependencyObject的Person类的应用程序。我没有设置名字和姓氏属性,我没有看到DependencyProperty.UnsetValue,而是一个空白的TextBox,里面只有一个逗号。

(一般情况下,你不应该在你的业务对象上使用依赖属性。坚持使用INotifyPropertyChanged并节省大量的麻烦。)

将代码发布到绑定对象,也许我可以发现问题。

public class Person : DependencyObject
{

    public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register("FirstName", typeof(string), typeof(Person), new FrameworkPropertyMetadata());

    public string FirstName {
        get { return (string)GetValue(FirstNameProperty); }
        set { SetValue(FirstNameProperty, value); }
    }

    public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register("LastName", typeof(string), typeof(Person), new FrameworkPropertyMetadata());

    public string LastName {
        get { return (string)GetValue(LastNameProperty); }
        set { SetValue(LastNameProperty, value); }
    }

}

-

<TextBox IsReadOnly="True">
    <TextBox.Text>
        <MultiBinding StringFormat="{}{1}, {0}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
        </MultiBinding>
    </TextBox.Text>
</TextBox>

-

public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();
    }

    private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        var p = new Person();
        //p.FirstName = "Josh";
        //p.LastName = "Einstein";          
        DataContext = p;
    }
}