WPF使用代碼進行綁定

來源:互聯網
上載者:User

關於WPF綁定機制,給我們帶來了很大的方便,我們都瞭解在WPF綁定中使用XAML方式可以這樣做,代碼如下:

1 <Window x:Class="WpfApplication1.Window1"
2     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4     Title="Window1" Height="300" Width="300">
5     <Grid>
6         <TextBlock Name="txtbShow" Height="21" Margin="47,32,111,0" VerticalAlignment="Top" Text="{Binding ElementName=txtInput,Path=Text}" />
7         <TextBox Name="txtInput" Height="23" Margin="47,70,111,0" VerticalAlignment="Top" />
8     </Grid>
9 </Window>

但是如果在cs檔案中如何進行控制項的綁定呢?看下面代碼:

1 //執行個體化綁定對象
2 Binding textBinding = new Binding();
3 //設定要繫結來源控制項
4 textBinding.Source = this.txtInput;
5 //設定要綁定屬性
6 textBinding.Path = new PropertyPath("Text");
7 //設定綁定到要綁定的控制項
8 this.txtbShow.SetBinding(TextBlock.TextProperty, textBinding);

從上面代碼可以看出,WPF用代碼的方式也能很好的進行綁定操作。如果我們要執行雙向繫結,或者設定Converter的時候怎麼辦呢?我們只要設定Binding的這兩個屬性Binding.Converter,Binding.Mode就可以了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.