<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          dotnet9站長:WPF中的數(shù)據(jù)綁定表達(dá)式!

          共 15741字,需瀏覽 32分鐘

           ·

          2021-05-16 10:57

          有很多文章討論綁定的概念,并講解如何使用StaticResources和DynamicResources綁定屬性。這些概念使用WPF提供的數(shù)據(jù)綁定表達(dá)式。在本文中,讓我們研究WPF提供的不同類型的數(shù)據(jù)綁定表達(dá)式。

          介紹

          數(shù)據(jù)綁定是一種強(qiáng)大的技術(shù),它允許數(shù)據(jù)在UI元素和業(yè)務(wù)模型之間流動。當(dāng)業(yè)務(wù)模型中的數(shù)據(jù)發(fā)生變化時,它會自動將更改反映到UI元素上。

          ModelsDescription
          OneWaySource → Destination
          TwoWaySource ←→ Destination
          OneWayToSourceSource ← Destination
          OneTimeSource → Destination (only once)

          這可以通過WPF提供的不同類型的數(shù)據(jù)綁定表達(dá)式來實現(xiàn)。

          數(shù)據(jù)綁定表達(dá)式的類型如下所示。

          • DataContext綁定
          • RelativeSource綁定
          • 集合當(dāng)前項綁定

          1、DataContext綁定

          DataContext是一個依賴屬性,它是綁定的默認(rèn)源。Datacontext沿著邏輯樹繼承。因此,如果您設(shè)置一個DataContext來控制邏輯樹中的所有子元素,它也將引用同一個DataContext,除非并且直到顯式指定了另一個源。

          讓我們舉個例子來更詳細(xì)地理解它。

          1.1 創(chuàng)建一個類Book,如下所示。

          public class Book 
          {  
              public string Name 
              {  
                  get;  
                  set;  
              }  
              public string Author 
              {  
                  get;  
                  set;  
              }  
          }  

          1.2 添加一個XAML文件DataContextBinding.XAML并放置四個TextBlock,如下所示。

          <Grid VerticalAlignment="Center">  
          <Grid.RowDefinitions>
          <RowDefinition Height="40" />
          <RowDefinition Height="40" />
          </Grid.RowDefinitions>
          <Grid.ColumnDefinitions>
          <ColumnDefinition Width="Auto" />
          <ColumnDefinition Width="Auto" />
          </Grid.ColumnDefinitions>
          <TextBlock Text="Book Name:" FontWeight="Bold" />
          <TextBlock Grid.Column="1" />
          <TextBlock Text="Author:" FontWeight="Bold" Grid.Row="1" />
          <TextBlock Grid.Row="1" Grid.Column="1" />
          </Grid>

          現(xiàn)在,讓我們看看如何使用這個DataContext屬性來顯示數(shù)據(jù)。

          它有兩種用法,如下所示。

          • 1.使用{Binding}表達(dá)式

          用于直接綁定DataContext。

          創(chuàng)建類Book的實例,初始化其屬性,并將類的Name屬性分配給Window的DataContext屬性。

          public partial class DataContextBindingWindow 
          {  
              public DataContextBinding() 
              {  
                  InitializeComponent();  
                  //Create the instance  
                  Book book = new Book();  
                  //initialize the properties  
                  book.Name = "Computer Networking";  
                  //Assign the Property as DataContext  
                  this.DataContext = book.Name;  
              }  
          }  

          由于DataContext是沿著邏輯樹和數(shù)據(jù)book繼承的,因此Name被綁定到Control Window。Window的所有子元素也將引用同一個對象(book.Name)。

          要顯示數(shù)據(jù),請將DataContext與Textblock綁定,如下所示。

          <TextBlock Text="Book Name:" FontWeight="Bold"/>  
          <TextBlock Text="{Binding}" Grid.Column="1" />

          輸出

          1. 使用{Binding Property}表達(dá)式

          綁定Datacontext的屬性。

          創(chuàng)建類Book的實例,初始化其屬性并將類的實例(Book)分配給Window的DataContext屬性。

          Book book = new Book();  
          //initialize the properties  
          book.Name = "Computer Networking";  
          book.Author = "James F. Kurose";  
          //Assign the instance as DataContext  
          this.DataContext = book;  

          現(xiàn)在,讓我們看看輸出。

          由于綁定表達(dá)式{Binding}用于綁定Book類型的DataContext對象,因此調(diào)用ToString()方法,并將數(shù)據(jù)顯示為字符串。為了以正確的格式顯示數(shù)據(jù),我們必須將數(shù)據(jù)對象的屬性與TextBlock綁定,如下所示:

          <TextBlock Text="Book Name:" FontWeight="Bold"/>  
          <TextBlock Text="{Binding Name}" Grid.Column="1" />
          <TextBlock Text="Author:" FontWeight="Bold" Grid.Row="1" />
          <TextBlock Text="{Binding Author}" Grid.Row="1" Grid.Column="1"/>

          綁定表達(dá)式{Binding Name}用于綁定DataContext綁定的Name屬性。

          輸出

          2、RelativeSource 綁定

          RelativeSource是一個屬性,它用相對關(guān)系設(shè)置綁定源以綁定目標(biāo)。此擴(kuò)展主要用于必須將元素的一個屬性綁定到同一元素的另一個屬性時。

          RelativeSource有四種類型,如下所示。

          1. Self
          2. FindAncestor
          3. TemplatedParent
          4. PreviousData

          讓我們一個一個詳細(xì)地探討一下。

          2.1 Self

          Self用于綁定源和綁定目標(biāo)相同的場景中。對象的一個屬性與同一對象的另一個屬性綁定。

          例如,讓我們?nèi)∫粋€高度和寬度相同的橢圓。

          在XAML文件中添加下面給出的代碼。寬度屬性與高度屬性相對綁定。

          <Grid>  
          <Ellipse Fill="Black" Height="100" Width="{Binding RelativeSource={RelativeSource Self},Path=Height}">
          </Ellipse>
          </Grid>

          輸出

          如果改變橢圓的高度,寬度也會相對變化。

          2.2 FindAncestor

          顧名思義,當(dāng)綁定源是綁定目標(biāo)的祖先(父級)之一時使用此選項。使用FindAncestor擴(kuò)展,可以找到任何級別的祖先。

          讓我們舉個例子來更清楚地理解它。

          步驟

          創(chuàng)建XAML,它表示下面給出的元素的邏輯樹。

          <Grid Name="Parent_3">  
          <StackPanel Name="Parent_2">
          <Border Name="Parent_1">
          <StackPanel x:Name="Parent_0" Orientation="Vertical">
          <Button></Button>
          </StackPanel>
          </Border>
          </StackPanel>
          </Grid>

          現(xiàn)在,讓我們使用FindAncestor擴(kuò)展將祖先的Name屬性綁定到子元素button的Content屬性。

          <Grid Name="Parent_3">  
          <StackPanel Name="Parent_2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100">
          <Border Name="Parent_1">
          <StackPanel x:Name="Parent_0" Orientation="Vertical">
          <Button Height="50" Content="{Binding RelativeSource={RelativeSource FindAncestor,
          AncestorType={x:Type StackPanel},
          AncestorLevel=2},Path=Name}"></Button>
          </StackPanel>
          </Border>
          </StackPanel>
          </Grid>

          輸出

          AncestorType為“StackPanel”與AcestorLevel為“2”組合,將button的content屬性與StackPanel的Name屬性(Parent_2)綁定在一起。

          2.3 TemplatedParent

          TemplatedParent是一個屬性,它使您能夠創(chuàng)建一個包含少量未知值的控件模板。這些值取決于應(yīng)用ControlTemplate的控件的屬性。

          讓我們舉個例子來更詳細(xì)地理解它

          步驟

          1. 為按鈕創(chuàng)建一個ControlTemplate,如下所示。
          <Window.Resources>  
          <ControlTemplate x:Key="template">
          <Canvas>
          <Ellipse Height="110" Width="155"
          Fill="Black"/>
          <Ellipse Height="100" Width="150"
          Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}">
          </Ellipse>
          <ContentPresenter Margin="35"
          Content="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content}"/>
          </Canvas>
          </ControlTemplate>
          </Window.Resources>

          在上面給出的代碼中,橢圓的Fill屬性和ContentPresenter的Content屬性依賴于將應(yīng)用此模板的控件的屬性值。

          1. 添加一個按鈕并對其應(yīng)用模板。
          <Button Margin="50" Background="Beige" Template="{StaticResource template}" Height="0" Content="Click me" FontSize="22">  
          </Button>

          在應(yīng)用模板時,按鈕的Background(Beige)與橢圓的Fill屬性相對綁定,Content(Click me)與ContentPresenter的Content屬性相對綁定。依賴值生效并給出以下輸出。

          輸出

          2.4 PreviousData

          這是相對使用最少的方式。當(dāng)數(shù)據(jù)被分析時,這就出現(xiàn)了,我們需要表示值相對于以前數(shù)據(jù)的變化。

          讓我們舉個例子來更詳細(xì)地理解它。

          步驟

          1. 創(chuàng)建一個類Data并實現(xiàn)INotifyPropertyChanged接口,如下所示
          public class DataINotifyPropertyChanged 
          {  
              public int DataValue 
              {  
                  get;  
                  set;  
              }  
              public event PropertyChangedEventHandler PropertyChanged;  
              protected void OnPropertyChanged(string PropertyName) 
              {  
                  if (null != PropertyChanged) 
                  {  
                      PropertyChanged(this,  
                          new PropertyChangedEventArgs(PropertyName));  
                  }  
              }  
          }   
          1. 創(chuàng)建一個Data類型的列表并將其指定為DataContext。
          public RelativeSourcePreviousData() 
          {  
              InitializeComponent();  
              List < Data > data = new List < Data > ();  
              data.Add(new Data() 
              {  
                  DataValue = 60  
              });  
              data.Add(new Data() 
              {  
                  DataValue = 100  
              });  
              data.Add(new Data() 
              {  
                  DataValue = 120  
              });  
              this.DataContext = data;  
          }   
          1. 在XAML文件中添加ItemsControl。
          <ItemsControl ItemsSource="{Binding}"></ItemsControl>
          1. 為其創(chuàng)建ItemsPanel模板,如下。
          <ItemsControl ItemsSource="{Binding}">  
          <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
          <StackPanel Orientation="Vertical" />
          </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
          </ItemsControl>
          1. 現(xiàn)在,為了正確地表示數(shù)據(jù),創(chuàng)建DataTemplate,如下所示。
          <ItemsControl.ItemTemplate>  
          <DataTemplate>
          <StackPanel Orientation="Horizontal">
          <Grid Margin="30,20,0,0">
          <Rectangle Width="80" Height="{Binding DataValue}" Fill="Blue" />
          <TextBlock Foreground="White" Margin="35,0,0,0" Text="{Binding DataValue}"></TextBlock>
          </Grid>
          <TextBlock Margin="30,20,0,0" Text="Previous Data:"></TextBlock>
          <TextBlock VerticalAlignment="Center" Margin="5,20,0,0" Text="{Binding
          RelativeSource={RelativeSource PreviousData}, Path=DataValue}" />
          </StackPanel>
          </DataTemplate>
          </ItemsControl.ItemTemplate>

          輸出

          藍(lán)色框的高度是列表中項目的值,舊數(shù)據(jù)顯示在右側(cè)。該項的第一個值為“60”。因此,第一項沒有舊值。

          3、集合當(dāng)前項綁定

          在處理集合時使用。使用這個綁定表達(dá)式,您可以非常容易地讀取SelectedItem的屬性。斜杠是一種特殊運(yùn)算符,用于處理集合中的當(dāng)前項。

          下面給出了三種表達(dá)式。

          1. {Binding / }
          2. {Binding Collection / }
          3. {Binding Collection / Property}

          3.1 {Binding / }

          此表達(dá)式用于綁定DataContext中的當(dāng)前項。

          讓我們采取一個示例:

          在下面給出的示例中,DataContext是字符串類型的國家/地區(qū)的集合,并且與Listbox綁定在一起。

          步驟

          1. 創(chuàng)建一個Countries類并添加一個GetCountriesName()方法,該方法返回string數(shù)據(jù)類型的國家的集合,如下所示。
          public class Countries 
          {  
              public static List <string> GetCountriesName() 
              {  
                  List <string> countries = new List <string> ();  
                  foreach(CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) 
                  {  
                      RegionInfo country = new RegionInfo(culture.LCID);  
                      if (!countries.Contains(country.EnglishName))  
                          countries.Add(country.EnglishName);  
                  }  
                  countries.Sort();  
                  return countries;  
              }  
          }  
          1. 添加一個XAMl文件,一個ListBox和TextBlock,如下所示。
          <DockPanel Name="Collection">  
          <ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True">
          </ListBox>
          <TextBlock DockPanel.Dock="Top" />
          </DockPanel>
          1. 創(chuàng)建類Countries的實例并將Countries集合指定為DataContext。
          public CurrentItemCollection() 
          {  
              InitializeComponent();  
              Countries countries = new Countries();  
              this.DataContext = countries.GetCountriesName()  

          1. 綁定TextBlock的Text屬性以將其綁定到集合的當(dāng)前選定項,如下所示。
          <TextBlock DockPanel.Dock="Top" Text="{Binding /}" />

          輸出

          一旦列表項被選中,它將在右側(cè)顯示所選國家/地區(qū)。

          3.2 {Binding Collection /}

          此表達(dá)式用于綁定DataContext中集合屬性的當(dāng)前項。

          例如,

          DataContext是Countries類

          Collection屬性是CounriesList,它與ListBox綁定。

          步驟

          1. 使用上面創(chuàng)建的類似的國家類,只是略有不同。創(chuàng)建返回類型為RegionInfo的方法。
          public static List <RegionInfo> GetCountries() 
          {  
              List <RegionInfo> countries = new List <RegionInfo> ();  
              foreach(CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) 
              {  
                  RegionInfo country = new RegionInfo(culture.LCID);  
                  if (countries.Where(p => p.Name == country.Name).Count() == 0)  
                      countries.Add(country);  
              }  
              return countries.OrderBy(p => p.EnglishName).ToList();  
          }
          1. 添加RegionInfo類型的CountriesList屬性。
          private List <RegionInfo> countries = null;  
          public List <RegionInfo> CountriesList 
          {  
              get 
              {  
                  if (countries == null)  
                      countries = GetCountries();  
                  return countries;  
              }  
          }  

          下面是CountriesList集合中的值的截圖。

          1. 將類Countries指定為DataContext,并將Listbox與DataContext的CountriesList屬性綁定。
          <Window.Resources>  
          <vm:Countries x:Key="Countries"></vm:Countries>
          </Window.Resources>
          <Grid>
          <DockPanel Name="Collection" DataContext="{StaticResource Countries}">
          <ListBox ItemsSource="{Binding CountriesList}" IsSynchronizedWithCurrentItem="True">
          <ListBox.ItemTemplate>
          <DataTemplate>
          <TextBlock Text="{Binding EnglishName}"></TextBlock>
          </DataTemplate>
          </ListBox.ItemTemplate>
          </ListBox>
          </DockPanel>
          </Grid>
          1. 要計算CountriesList屬性的當(dāng)前項,請綁定TextBlock的Text屬性,如下所示。
          <TextBlock DockPanel.Dock="Top" Text="{Binding CountriesList/}" HorizontalAlignment="Center" FontSize="16" VerticalAlignment="Center" />

          輸出

          右側(cè)顯示DataContext(CountriesList)中集合的當(dāng)前項(CountriesList)。

          3.3 {Binding Collection / Property}

          此表達(dá)式用于綁定DataContext中集合的當(dāng)前項的屬性。

          例如,如果必須計算CountriesList集合的當(dāng)前項的特定屬性。

          在這個例子中,我想顯示屬性“EnglishName”的值。

          為此,綁定TextBlock的Text屬性,如下所示。

          <TextBlock DockPanel.Dock="Top" Text="{Binding CountriesList/EnglishName}" />

          輸出

          現(xiàn)在,當(dāng)列表中的項被選中時,它顯示屬性“EnglishName”的值。

          結(jié)論

          我已經(jīng)詳細(xì)介紹了所有的數(shù)據(jù)綁定表達(dá)式。我希望這有助于您理解綁定的概念和WPF提供的表達(dá)式。







          回復(fù) 【關(guān)閉】學(xué)關(guān)
          回復(fù) 【實戰(zhàn)】獲取20套實戰(zhàn)源碼
          回復(fù) 【被刪】學(xué)
          回復(fù) 【訪客】學(xué)
          回復(fù) 【小程序】學(xué)獲取15套【入門+實戰(zhàn)+賺錢】小程序源碼
          回復(fù) 【python】學(xué)微獲取全套0基礎(chǔ)Python知識手冊
          回復(fù) 【2019】獲取2019 .NET 開發(fā)者峰會資料PPT
          回復(fù) 【加群】加入dotnet微信交流群

          谷歌靈魂插件,98%的程序員都好評!


          再見Vip,免費(fèi)看網(wǎng)飛影視大片!


          瀏覽 35
          點贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  天天干天天干天天天干 | 亚洲人在线观看 | 激情www | 火爆全网嫖妓达人金先生约战极品S空 | 日本少妇xxxx |