1. 程式人生 > >WPF 獲得DataTemplate中的控制元件

WPF 獲得DataTemplate中的控制元件

1、WPF 獲得DataTemplate中的控制元件, 下面這個示例是從ListBox中獲得ListBoxItem模板的控制元件資訊。

前臺程式碼:

<!--獲得模板中的控制元件-->

       <ListBox  Margin="12,32,0,0" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" Name="listBox1" SelectedIndex=

"0" Height="186" VerticalAlignment="Top" HorizontalAlignment="Left" Width="287">

           <ListBox.ItemTemplate>

               <DataTemplate x:Name=

"gridDataTemplate">          

                   <Grid>

                       

<Grid.ColumnDefinitions>

                           <ColumnDefinition Width="0.5*"/>

                           <ColumnDefinition Width="0.5*"/>

                           <ColumnDefinition Width="0.5*"/>

                           <ColumnDefinition Width="0.5*"/>

                       </Grid.ColumnDefinitions> 

                       <TextBlock Text="{Binding Path=ID}"/>

                       <TextBlock Grid.Column="1" x:Name="myName" Text="{Binding Path=Name}"/>

                       <TextBlock Grid.Column="2" Text="{Binding Path=Age}" Background="{Binding Path=Age, Converter={StaticResource BackgroundConverter}}"/>

                       <CheckBox Grid.Column="3" x:Name="myCheckBox" IsChecked="{Binding Path= ISBoy, Converter={StaticResource BoolConverter}}"/>

                   </Grid>

               </DataTemplate>

           </ListBox.ItemTemplate>

       </ListBox>

 資源:

<Window.Resources>

       <Con:BackgroundConverter x:Key="BackgroundConverter"/>

       <Con:BoolConverter x:Key="BoolConverter"/>

</Window.Resources>

  

 

<Button Height="23" HorizontalAlignment="Left" Margin="35,251,0,0" Name="button1" VerticalAlignment="Top" Width="209" Click="button1_Click">GetControlFromDataTemplate</Button>

  

 

後臺程式碼:

public Window1()

 {

     InitializeComponent();

    

     listBox1.DataContext = GetDataTable();

         

  }

 Click事件:關鍵程式碼

private void button1_Click(object sender, RoutedEventArgs e)

  {

 

      ListBoxItem myListBoxItem = (ListBoxItem)listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.SelectedItem);

      ContentPresenter contentpresenter = FindFirstVisualChild<ContentPresenter>(myListBoxItem);

      DataTemplate MyDataTemplate = contentpresenter.ContentTemplate;

      TextBlock myTextBlock = MyDataTemplate.FindName("myName", contentpresenter) as TextBlock;

      if (myTextBlock != null)

      {

          MessageBox.Show(myTextBlock.Text);

      }

 

}

  

 

資料來源:當然也可以自己連線資料庫獲得資料來源

private DataTable  GetDataTable()

     {

         DataTable data = new DataTable("MyDataTable");

          

         DataColumn ID = new DataColumn("ID");//第一列

         ID.DataType = System.Type.GetType("System.Int32");

         //ID.AutoIncrement = true; //自動遞增ID號

         data.Columns.Add(ID);

 

         //設定主鍵

         DataColumn[] keys = new DataColumn[1];

         keys[0] = ID;

         data.PrimaryKey = keys;

 

         data.Columns.Add(new DataColumn("Name",typeof(string)));//第二列

         data.Columns.Add(new DataColumn("Age",typeof(string)));//第三列

         data.Columns.Add(new DataColumn("ISBoy", typeof(Int16)));//第三列

 

         data.Rows.Add(1,"  XiaoM","  20", 1);

         data.Rows.Add(2,"  XiaoF","  122", 0);

         data.Rows.Add(3,"  XiaoA", "  29", 1);

         data.Rows.Add(4,"  XiaoB", "  102", 0);

         return data;

     }

  

值轉換:BackgroundConverter類是改變顏色,BoolConverter是將Bool互相轉換Int

public class BackgroundConverter : IValueConverter

   {

       #region IValueConverter Members

 

       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

       {

           Color color = new Color();

           int num = int.Parse(value.ToString());

           if (num > 100)

               color = Colors.Yellow;

           else if (num < 50)

               color = Colors.LightGreen;

           else

               color = Colors.LightPink;

           return new SolidColorBrush(color);

       }

 

       public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

       {

           throw new NotImplementedException();

       }

 

       #endregion

   }

   public class BoolConverter : IValueConverter

   {

       #region IValueConverter Members

 

       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

       {

           bool flag = false;

           

           if (1 == int.Parse(value.ToString()))

           {

               flag = true;

           }

 

           if( 0 == int.Parse(value.ToString()))

               flag = false;

 

           return flag;

       }

 

       public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

       {

           if ((bool)value)

           {

               return 1;

           }

           else

               return 0;

       }

 

       #endregion

   }

  

 //關鍵函式

public T FindFirstVisualChild2<T>(DependencyObject obj, string childName) where T : DependencyObject

      {

          for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)

          {

              DependencyObject child = VisualTreeHelper.GetChild(obj, i);

              if (child != null && child is T && child.GetValue(NameProperty).ToString() == childName)

              {

                  return (T)child;

              }

              else

              {

                  T childOfChild = FindFirstVisualChild2<T>(child, childName);

                  if (childOfChild != null)

                  {

                      return childOfChild;

                  }

              }

          }

          return null;

      }

  

 效果圖: 當選中第一項,然後單擊"GetControlFromDataTemplate"按鈕,則彈出第一項中控制元件的內容XiaoM。