【Win8】– 資料繫結&自訂轉換

來源:互聯網
上載者:User

資料繫結(介面裡面也可以定義事件)
1、

 (1)簡單的綁定和wp7/wp8類似(這裡不再寫了,很相似的,請參考)
        隨機產生5位元據的代碼: 

dog.Name=Guid.NewGuid().ToString().Substring(0,5);

  (2)選擇模式
         將LictView中的對勾去掉:<ListView SelectionMode="None" ...> 單一:Single 多選:Multiple
  (3)IList<object> objs=lv1.SelectedItems; //對象為選中項的資料內容
  (4)IsItemClickedEnabled

//首先設定 IsItemClickEnabled="True" ,啟用ItemClick事件,然後監聽ItemClick事件,e.ClickedItem為點擊那一項的DataContextPerson p= e.ClickItem as Person;MessageDialog mdialog = new MessageDialog(p.Name);mdialog.ShowAsync(); //對話方塊顯示的非同步作業

  (5)在集合中添加元素(綁定到ListView中)
         需要用到 ObservableCollection<> 泛型,在Using System.Collections.ObjectModl 命名空間下,除了資料繫結以外,一般其他的集合用 List<> 就ok了,

// private List<string> ls=new List<string>();ObservableCollection<string> ls = new ObservableCollection<string>();  protected override void OnNavigatedTo(NavigationEventArgs e)  {     if (e.NavigationMode== NavigationMode.New)     {        ls.Add("kefira");        ls.Add("kk");        lv.ItemsSource = ls; //資料繫結到ListView中時,顯示資料只需要寫出該行代碼即可,但是也有人在xaml中修改ListView的屬性為 ItemSource={Binding},                             // 然後寫入後台代碼 lv.DataContent=ls;效果是一樣的,意義也是一樣的,多此一舉而已嘛     }   }  private void Button_Click_1(object sender, RoutedEventArgs e)  {     ls.Add(DateTime.Now.Millisecond.ToString());   }

運行結果

       

2、自訂轉換

    ComboBox -- 下拉式清單方塊 PlipView -- 左右選擇顯示 以及 自訂轉換
     轉換器的一般命名規則:XX--XX轉換器(例如UI到Model,BoolVisibilityConverter)
     樣本:判斷該國家是否是聯合國,是的話顯示聯合國圖片,不是則不顯示

     <1>定義一個CountryInfo類

 

using System.ComponentModel;namespace _1自訂轉換{  public   class CountryInfo:INotifyPropertyChanged    //別忘了引入命名空間System.ComponentModel    {        private void FirePropertyChanged(string propName)        {            if (PropertyChanged != null)            {                PropertyChanged(this, new PropertyChangedEventArgs(propName));            }        }        private string _name;        public string Name        {            get { return _name; }            set { _name = value; FirePropertyChanged("Name"); }        }        private string _ImagePath;        public string ImagePath        {            get { return _ImagePath; }            set { _ImagePath = value; FirePropertyChanged("ImagePath"); }        }        private bool _isUnNum;  //判斷是否是聯合國成員        public bool IsUnNum        {            get { return _isUnNum; }            set { _isUnNum = value; FirePropertyChanged("IsUnNum"); }        }        public event PropertyChangedEventHandler PropertyChanged;    }}

 

     <2>設計MainPage.xaml介面:  (先把照片放到Image檔案夾下)

 <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">        <ComboBox x:Name="combCountry" HorizontalAlignment="Left" Margin="54,81,0,0" VerticalAlignment="Top" Width="387" Height="71">            <ComboBox.ItemTemplate>                <DataTemplate>                    <StackPanel Orientation="Horizontal">                        <Image Source="{Binding ImagePath}" Height="50" Width="50" />                        <TextBlock Name="{Binding Name}" />                    </StackPanel>                </DataTemplate>            </ComboBox.ItemTemplate>        </ComboBox>        <FlipView x:Name="fvCountry" HorizontalAlignment="Left" Margin="354,270,0,0" VerticalAlignment="Top" Width="610" Height="315">            <FlipView.ItemTemplate>                <DataTemplate>                    <Grid Background="Blue">                        <Grid.RowDefinitions>                            <RowDefinition></RowDefinition>                            <RowDefinition></RowDefinition>                        </Grid.RowDefinitions>                        <Image Source="{Binding ImagePath}" Grid.RowSpan="2"></Image>                        <Image Source="ms-appx:///Image/4.png" Height="70" Width="70" Visibility="{Binding IsUnNum}"/>  //在定義的時候IsNuNum是bool類                                                                                                                           型的,而在這裡轉換成了枚舉類型                                </Grid></DataTemplate>            </FlipView.ItemTemplate>        </FlipView>    </Grid>

    <3>代碼實現:
         

   protected override void OnNavigatedTo(NavigationEventArgs e)        {            if (e.NavigationMode== NavigationMode.New)            {                List<CountryInfo> listCountry = new List<CountryInfo> ();                 listCountry.Add(new CountryInfo { Name = "中國" , ImagePath="ms-appx:///Image/1.png" ,IsNuNum = true});                listCountry.Add(new CountryInfo { Name = "日本" , ImagePath="ms-appx:///Image/2.png" ,IsNuNum = false});                listCountry.Add(new CountryInfo { Name = "美國" , ImagePath="ms-appx:///Image/3.png" ,IsNuNum = true});                combCountry.ItemsSource = listCountry;  //Itemsource繼承於ItemTemplate            }                   }   

         馬上運行了下,卻發現 “日本” 也被判定成了是聯合國的成員(因為聯合國的圖片4.png也顯示了出來),這裡,我們就必須要自訂轉換了(這才是重點)。
     <4>首先需要定義轉換器的類BoolVisibilityConverter,轉換器要實現IValueConverter介面

using Windows.UI.Xaml;using Windows.UI.Xaml.Data;namespace _1自訂轉換.Common{   public  class BoolVisibilityConverter : IValueConverter    //IvalueConverter的命名空間為Windows.UI.Xaml.Data;    {        object IValueConverter.Convert(object value, Type targetType, object parameter, string language)        {            //這裡的value是Model中的 資料,傳回值是轉換後UI中的資料            bool b = (bool)value;            return b ? Visibility.Visible : Visibility.Collapsed;        }        //如果資料繫結是TwoWay形式的,那麼還需要實現該ConvertBack        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)        {            Visibility v = (Visibility)value;   //Visibility的命名空間為 Windows.UI.Xaml;            return v == Visibility.Visible;        }    }}

########解釋下:
Convert方法用於把綁定模型的屬性類型轉換為被綁定UI元素的資料類型,value為轉換前資料,把轉換後資料以傳回值形式返回。
ConvertBack方法用於當TwoWay綁定的時候UI值發生變化方向修改Model屬性值的時候做轉換的。

 

    <5>然後再轉到MainPage.xaml中設計
          首先添加命名空間: xmlns:common="using:_1自訂轉換.Common"     //common是隨意的命名
          然後定義資源:

<Page.Resources>      <common:BoolVisibilityConverter x:Key="boolVisConverter"></common:BoolVisibilityConverter></Page.Resources>

          最後,在定義的 “聯合國圖片4.png” 的 Image 標籤下的 Visibility 屬性中再加上:Converter={StaticResource boolVisConverter}
  ok,自訂的轉換完成,運行程式。如:(當底片轉換到 “中國” 或 “美國” 時,聯合國的照片顯示;但底片是 “日本” 時,聯合國的圖片不顯示)

               

---後記:這節是資料繫結和自訂轉換的簡單練習,依舊來自於傳智播客視頻的學習,分享給同樣愛好win8的朋友們!@_@

 下篇文章將會寫到動畫和非同步編程。

 

聯繫我們

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