问题描述
|
我是WPF新手,在用户控件内有一个UserControl,我想绑定到存储在dataContext中的项目类型Property(称为\“ AssignType \”)... \“ AssignType \”确定要保留的控件\“值\”属性。
AssignType可以是Textbox,Richtextbox,ComboBox,DatePicker,RadioButton等
值字段需要使用2种方式绑定到\“ AssignType \”控件-此外,还需要绑定项目数据(例如组合源)
我设法做到这一点的唯一方法是创建一个自定义控件,检查DataContext并手动建立“分配的控件”,然后将所有更改应用于“控件已更改事件”,
我的问题是,这似乎不是“非常WPF” ...
做这样的任务的正确方法是什么?
(样本负载电流法)
Select Case AssignedType
Case Items.FieldTypes.IsText,Tb = New TextBox
Try
If Not IsNothing(Source.ValueItem) Then _
Tb.Text = Source.ValueItem
Catch
End Try
Tb.SetBinding(TextBox.TextProperty,BindingSource)
AddChild(Tb)
Case Items.FieldTypes.IsDropDownValue
cbo = New ComboBox
cbo.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
PopulateComboValues(cbo,Source)
AddChild(cbo)
Case Items.FieldTypes.IsDateValue
Dt = New DatePicker
Dt.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
Try
If IsDate(Source.ValueItem) Then Dt.SelectedDate = Convert.ToDateTime(Source.ValueItem)
Catch
End Try
Dt.Margin = New Thickness(5,5,0)
AddChild(Dt)
Case Items.FieldTypes.IsLargeText
Rtf = New RichTextBox
Rtf.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
Try
If Not IsNothing(Source.ValueItem) AndAlso Source.ValueItem.Trim <> \"\" Then
Dim ms As MemoryStream = New MemoryStream(ASCIIEncoding.Default.GetBytes(Source.ValueItem))
Rtf.Selection.Load(ms,DataFormats.Xaml)
End If
Rtf.SpellCheck.IsEnabled = True
Catch
End Try
Rtf.Height = 100
AddChild(Rtf)
Case Items.FieldTypes.IsImageList
解决方法
确实,它不是很WPF。这就是我们使用DataTemplates的目的。