WPF學習筆記(資料繫結篇2)

來源:互聯網
上載者:User

接上篇文章WPF 學習筆記(資料繫結篇)

BindToMethod

這個樣本功能是將標準溫度轉化為:攝氏度Celsius或者華氏度Fahrenheit,此轉化是通過調用一個public string ConvertTemp(double degree, TempType temptype)方法獲得最終的結果的。

此樣本相對還是比較複雜的,首先聲明一個方法類型的資料來源:

 

<ObjectDataProvider ObjectType="{x:Type local:TemperatureScale}"
MethodName="ConvertTemp" x:Key="convertTemp">
<ObjectDataProvider.MethodParameters>
<system:Double>0</system:Double>
<local:TempType>Celsius</local:TempType>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

此XAML描述了使用TemperatureScale類執行個體的ConvertTemp方法作為資料來源,當然,我們需要給一個預設的調用資料。

然後我們希望將文字框的內容綁定到方法的第一個參數上:

<TextBox.Text>
<Binding Source="{StaticResource convertTemp}" Path="MethodParameters[0]"
BindsDirectlyToSource="true" UpdateSourceTrigger="PropertyChanged"
Converter="{StaticResource doubleToString}">
<Binding.ValidationRules>
<local:InvalidCharacterRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>

這裡需要指定將字串轉化為double的轉化器,而且還要有一個防止使用者錄入錯誤的資料的校正器。

第二步,我們需要將下拉框綁定到第二個參數:

<ComboBox Grid.Row="1" Grid.Column="2"
SelectedValue="{Binding Source={StaticResource convertTemp},
Path=MethodParameters[1], BindsDirectlyToSource=true}">
<local:TempType>Celsius</local:TempType>
<local:TempType>Fahrenheit</local:TempType>
</ComboBox>

和上面的一樣,綁定到第二個參數上。

這裡有個巧妙的地方,XAML直接將對象執行個體Celsius和Fahrenheit作為ComboBox的明細了,我們看見下拉框顯示正確,而且可以不用轉換器直接作為第二個參數。

最後就是綁定結果了:

<Label Content="{Binding Source={StaticResource convertTemp}}"
Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2"/>

HierarchicalDataTemplate

在這裡例子中,我們將看見:

  • 具有階層的資料繫結到樹控制項和菜單控制項;
  • 在延伸的代碼中,你將看見這種綁定同樣支援事件跟蹤。

 

在此樣本中,包含一個階層的資料對象:

在綁定到樹控制項和菜單時,是直接綁定的:

<TreeViewItem ItemsSource="{Binding Source={StaticResource MyList}}" Header="My Soccer Leagues" />

<MenuItem Header="My Soccer Leagues" ItemsSource="{Binding Source={StaticResource MyList}}" />

那麼控制項如何知道他的明細使用哪個集合屬性呢?這裡就靠HierarchicalDataTemplate了。

<HierarchicalDataTemplate DataType = "{x:Type src:League}"
ItemsSource = "{Binding Path=Divisions}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>

上面的XAML作為資源定義,描述為類型League的明細使用Divisions屬性。

最後我對這個樣本程式進行了改造,首先修改資料類的所有List類型改為ObservableCollection,以便集合實現更改通知。然後我添加了一個菜單:AddTeam,單擊此菜單時,我向資料來源添加了一個Team對象,我發現繫結系統都自動檢測到這個改變了。

因此,我們可以利用此特性,定義一個描述菜單的實體結構,然後綁定到菜單上,這樣,實際的代碼將操控與特定菜單實現無關的實體,從而達到隔離的目的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.