0

我有一个文本框,它使用多重绑定 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>

请帮我。

4

2 回答 2

0

只需给出 fallbackvalue="" 并查看

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

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

于 2011-01-25T05:10:02.230 回答
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;
    }
}
于 2011-01-25T05:15:34.817 回答