为什么这儿TemplateBinding不起作用了—研究WPF Binding(一)
工作中,寫自定義控件,遇到一個奇怪的問題。場景是這樣的:一個ListBox或其他ItemsControl顯示數據列表,下方一個TextBlock顯示列表中選定的值,代碼大概是這樣的(做了簡化):
<Border Background="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"><StackPanel><ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent},Path=TimeDataSource.Months}"SelectedValue="{TemplateBinding Month}" VerticalContentAlignment="Top"></ListBox><TextBlock Text="{TemplateBinding Month}"/></StackPanel> </Border>Month是后臺定義的依賴屬性,現在的問題是,ListBox拿到了數據(1到12個月),但下方的TextBlock卻顯示不出列表的SelectedValue,必須把它的代碼換成這樣才行:
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Month}"/>用snoop抓取也會看到后面一種情形,Text屬性才能拿到值。顯然要查清楚問題所在必須研究一下TemplateBinding。
按照MSDN和網絡上看到的解釋,TemplateBinding主要用于模版,屬于優化的Binding但精簡了繼承內容引用和動態類型轉換等很多功能,它等效于:{Binding RelativeSource={RelativeSource TemplatedParent}}。看到這兒品味出什么了吧,對,類型轉換!它所綁定的依賴屬性Month是Int類型,而TextBlock的Text屬性是String類型,如果用普通Binding,WPF能自動幫你做轉換,而TemplateBinding就不行了。無獨有偶,幾個月前我寫過一個小控件,一個要求是輸入框(TextBox)前面的文本說明是可以設置的,比如“柜員賬號”或其他什么名稱,我定義的InputName屬性是String類型,用TemplateBinding和TextBlock綁在一起就可以正常運行。那就再定義一個String類型的依賴屬性,試試看:
public static readonly DependencyProperty MonthStringProperty =DependencyProperty.Register("MonthString", typeof(String), typeof(ControlTest),new FrameworkPropertyMetadata(DateTime.Now.Month.ToString()));public String MonthString{get { return GetValue(MonthStringProperty).ToString(); }set { SetValue(MonthStringProperty, value); }}前臺Xaml如下:
<Border Background="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"><StackPanel><TextBlock Text="{TemplateBinding MonthString}"/><ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent},Path=TimeDataSource.Months}"SelectedValue="{TemplateBinding Month}" VerticalContentAlignment="Top"></ListBox><TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Month}"/></StackPanel></Border>果然,數據能顯示了:
所以,可以得出:TemplateBinding的源和目標類型必須完全一致,如果它們之間需要類型轉換,只能改成{Binding RelativeSource}的形式,或者定義依賴屬性時注意一下類型,這里Month由于后面涉及一些計算必須定義為int。
轉載于:https://www.cnblogs.com/zxmoe992/archive/2013/06/08/3127030.html
總結
以上是生活随笔為你收集整理的为什么这儿TemplateBinding不起作用了—研究WPF Binding(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 方法概述
- 下一篇: vs2010 将.mc编译为.rc文件