如何访问ControlTemplate中的控件
本文关键字:ControlTemplate 控件 访问 何访问 | 更新日期: 2023-09-27 17:58:22
在我的WP8应用程序的App.xaml文件中,我定义了ControlTemplate如下:
<Application.Resources>
<ControlTemplate x:Name="AddReminderDialog">
<Canvas HorizontalAlignment="Center" Height="320" Width="260"
VerticalAlignment="Center" Background="White" Margin="110,178,110,238">
<TextBlock Foreground="Black" Text="Напомнить" FontSize="15" HorizontalAlignment="Center" Canvas.Left="92" Canvas.Top="38" />
<Button Name="btn1HourBef" BorderThickness="0" Click="NotificationButtonClick" Background="Black" Content="За час" Width="260" FontSize="15" Height="60" Margin="0,70,0,0"/>
<Button Name="btn30MinBef" BorderThickness="0" Click="NotificationButtonClick" Background="Black" Content="За 30 минут" Width="260" FontSize="15" Height="60" Margin="0,130,0,0"/>
<Button Name="btnOnArrDept" BorderThickness="0" Click="NotificationButtonClick" Background="Black" Content="По прилету/вылету" Width="260" FontSize="15" Height="60" Margin="0,190,0,0"/>
<Button Name="btnCancel" BorderThickness="0" Click="NotificationButtonClick" Background="Black" Content="Отменить" Width="260" FontSize="15" Height="60" Margin="0, 250, 0, 0" Visibility="Collapsed"/>
</Canvas>
</ControlTemplate>
</Application.Resources>
我使用它作为弹出的模板如下
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var image = sender as Image; //get the sender iamge
var modelItem = image.DataContext; //get image's data context
const double width = 260;
const double height = 280;
//get the flight id from image's tag property(which was binded in flightInfoDataTemplate)
flightID = Convert.ToString(image.Tag);
//define content for popup
var content = new ContentControl()
{
Width = width,
Height = height,
Background = new SolidColorBrush(Colors.Transparent)
};
//set the template of content to the contentTemplate, which was defined in app.xaml
content.Template = (ControlTemplate)Resources["AddReminderDialog"];
//set popup's datacontext to the image's datacontext
content.DataContext = modelItem;
//popup's child property is setting to our content
popup.Child = content;
popup.Height = height;
popup.Width = width;
popup.VerticalOffset = Application.Current.RootVisual.RenderSize.Height / 2 - height / 2;
popup.HorizontalOffset = Application.Current.RootVisual.RenderSize.Width / 2 - width / 2;
popup.IsOpen = true;
}
我使用这个弹出窗口来设置通知。当用户第一次点击图像时,btnCancel按钮应该是不可见的,因为没有什么可以取消的。当第二次点击图像时,btnCancel应变为可见以取消通知。默认情况下,我已将按钮可见性设置为折叠。但我不知道如何访问后面代码中的按钮,使其可见。所以我的问题是如何在代码后面更改按钮的可见性设置?
您可以这样做
private void SearchElement(DependencyObject targeted_control)
{
var count = VisualTreeHelper.GetChildrenCount(targeted_control); // targeted_control is the Canvas
if (count > 0)
{
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(targeted_control, i);
if (child is Button ) // specific button control
{
// do your logic
}
}
}
}