開發環境:VisualStudio2010 +Silverlight4
新建一個test.xaml,並添加ComboBox組合框控件,其Xaml代碼如下:
- <ComboBox x:Name="cmbBoxCategory" Height="28" Margin="105,69,182,0" VerticalAlignment="Top" SelectionChanged="cmbBoxCategory_SelectionChanged" DataContext="{StaticResource SharingObjectCategoryDataSource}" ItemsSource="{Binding CategoryCollection }" >
- <ComboBox.ItemTemplate>
- <DataTemplate x:Name="cmbTemplate">
- <StackPanel Orientation="Horizontal">
- <TextBox x:Name="txtID" Text="{Binding Path=ID}"/>
- <Image Source="{Binding Path=ImagePath}"/>
- <TextBlock x:Name="tbCategoryName" Text="Name"/>
- </StackPanel>
- </DataTemplate>
- </ComboBox.ItemTemplate>
- </ComboBox>
那麼我們如何獲取DataTemplate中的名爲txtID的TextBox控件或者其它控件呢?
在test.xaml.cs文件中不能夠直接引用名爲txtID的TextBox控件,即this.txtID是不能訪問的,因爲txtID只屬於DataTemplate模板的名稱空間範圍內(類似於參數的作用域),可參看Silverlight4文檔的TemplatePartAtrribute。我們如何獲得DataTemplate的TextBox控件呢?可用如下方式獲得:
方法一:
- TextBox txtBox = (TextBox)VisualTreeHelper.GetChild(this.cmbTemplate.LoadContent(), 0);
- // this.cmbTemplate.LoadContent()是獲取cmbTemplate名的DataTemplate的內容,該例中獲
- //得的是StackPanel,再通過VisualTreeHelper.GetChild()方法獲得屬於該StackPanel的控件,
- //可參看Silverlight4文檔的LoadContent()方法的使用
方法二:
- StackPanel panel = (StackPanel)this.cmbTemplate.LoadContent();
- TextBlock tbCategory=panel.FindName("tbCategoryName") as TextBlock;
- //可參看Silverlight4文檔的FindName()方法的使用
對於
TextBox txtBox = (TextBox)VisualTreeHelper.GetChild(this.cmbTemplate.LoadContent(), 0);
因爲它的Text的值是綁定數據源的ID屬性(如:{Binding Path=ID}),通過程序運行動態生成的值,因此通過這兩種方式獲得的TextBox的Text是空值,而對於tbCategoryName名的TextBlock,因爲它的Text值是固定的“Name”字符串,因此通過這兩種方法獲得的TextBlock的Text值爲“Name”。
如果我們想獲得選中的ComboBoxItem的TextBox的值或者Image的Source值,則可通過如下方式獲得:
- //test.xaml.cs代碼
- private void cmbBoxCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (this.cmbBoxCategory.SelectedItem!=null)
- {
- ComboBox item = sender as ComboBox;
- Category cat = (Category)this.cmbBoxCategory.SelectedItem;
- //Category類爲cmbBoxCategory組合框綁定的數據源類,然後再通過cat獲取該類中的ImagePath屬性即可
- this.imgObject.Source = new BitmapImage(new Uri(cat.ImagePath, UriKind.Relative));
- //imgObject爲test.xaml中的一個Image控件
- }
- }
可能有更好的方法獲得綁定數據源時動態生成的值,本人不才,還未想出該方法,可講究用上面的方法獲得,如果找到了相應方法就做更新。
原出處:http://blog.csdn.net/wackelbh/article/details/6003947#comments