您好我想从后面的代码访问 ResourceDictinory.xaml 文件中数据模板内的控件。
我的 ResFile1.xaml 内容
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate x:Key="btnTemplate1">
<StackPanel>
<TextBlock Name="txtBlock" Text="Abcd123" Foreground="Red"/>
<TextBox Name="txtBox" Text="textbox Text"/>
</StackPanel>
</DataTemplate>
好的。我在 MainPage.xaml 中像这样使用它
<phone:PhoneApplicationPage.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResFile1.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</phone:PhoneApplicationPage.Resources>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button HorizontalAlignment="Left" Height="152" Margin="106,221,0,0"
VerticalAlignment="Top" Width="256"
ContentTemplate="{Binding ConverterParameter=blabla, Converter={StaticResource TestResConverter}, Mode=OneWay, Source={StaticResource btnTemplate1}}"/>
</Grid>
我的 TestResConverter 类。(访问此类中数据模板内的元素)
public class ConverterTest : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is DataTemplate)
{
DataTemplate dataTemplate = value as DataTemplate;
//access elements
TextBox accessedTextbox = XXXMehod(dataTemplate);
accessedTextbox.Text = (string)parameter;//e.g change text property
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
如何访问 datatemplate 中的元素?什么是访问、编辑 DataTemplate 的替代方法?我还查看了 wpf 项目,但有些方法不存在 wp7。