2009-09-04 51 views
0

我試圖將此xaml文本框與驗證轉換爲C#,以便可以從代碼動態創建和填充該文本框。我陷入了創建驗證綁定。任何人都可以提供任何提示嗎?通過驗證將XAML文本框轉換爲C#

<TextBox Height="20" Width="200" > 
     <Binding RelativeSource="{x:Static RelativeSource.Self}" Path="Text" > 
      <Binding.ValidationRules> 
       <runtime:StandardTextBoxValidationRule/> 
      </Binding.ValidationRules> 
     </Binding> 
</TextBox> 
+0

你只是動態創建從WPF頁面中的文本? – 2009-09-04 17:53:29

+0

不,它是在與WPF頁面相同的程序集中的控件生成類中創建的。 – KithKann 2009-09-04 17:57:28

回答

1

你能做到像這樣:

TextBox textBox = // Get or create the text box 

var binding = new Binding(); 
binding.Source = RelativeSource.Self; 
binding.Path = new PropertyPath("Text"); 
binding.ValidationRules.Add(new StandardTextBoxValidationRule()); 
textBox.SetBinding(TextBox.TextProperty, binding); 
+0

我不得不添加以下內容才能正常工作 binding.Path = new PropertyPath(「Text」); 再次感謝。 – KithKann 2009-09-04 18:25:04

+0

很高興工作。如果其他人發現這一點,我也在我的回答中加上了這一點。 – 2009-09-04 19:03:02

+0

你也可以使用'新的綁定(「文本」)' – 2009-09-04 19:12:45