2011-01-25 44 views
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> 

請幫幫我。

+0

不清楚。試着看看VS中的輸出窗口,在那裏你可以看到所有的綁定錯誤。 DataContext中綁定了什麼=「{Binding}」? – SeeSharp 2011-01-25 04:47:34

回答

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; 
    } 
} 
0

只是給fallbackvalue =「」,看看

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

如果綁定不成功,即路徑綁定源沒有找到或值轉換器,如果有的話,失敗,一個DependencyProperty。如果您定義了一個,則返回UnsetValue,然後將目標屬性設置爲FallbackValue。