问题是:
我有一个带有监听器的“主页按钮”
private void Item_Tap(object sender, TappedRoutedEventArgs e)
{
if (this.Frame != null)
{
this.Frame.Navigate(typeof(Home));
}
}
如果我构建了一个用户控件,使用其中的“主页按钮”,我如何才能完成相同的导航?
** 我接近解决方案**。 这是用户控件:
public sealed partial class TopBarControl : UserControl
{
public Frame Frame { get; set; }
public object Parameter { get; set; }
public TopBarControl(Frame frame)
{
this.InitializeComponent();
this.Frame = frame;
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
var dateAndTime = DateTime.Now;
Date.Text = dateAndTime.Date.ToString("MM/dd/yyyy");
User.Text = localSettings.Values["userName"].ToString();
//SectionTitle.Text = Parameter.ToString();
}
private void GoHome_Tap(object sender, TappedRoutedEventArgs e)
{
if (this.Frame != null)
{
this.Frame.Navigate(typeof(Main_Menu));
}
}
}
在我的 xaml 用户控件上:
<Button Grid.Column="0" HorizontalAlignment="Right" BorderThickness="0">
<Image Source="/Assets/home_icon.png" Tapped="GoHome_Tap"/>
</Button>
关联到用户控件的页面
public WantedVehicles()
{
this.InitializeComponent();
}
private TopBarControl topBarControl;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Tit.Text = e.Parameter.ToString();
topBarControl.Frame = this.Frame;
topBarControl.Parameter = e.Parameter;
}
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
}
protected override void SaveState(Dictionary<String, Object> pageState)
{
}
但是按钮还不能用。
最佳答案
我明白你的问题。这是创建主页按钮的简单方法,您可以将其添加到应用程序的任何位置,它会导航到主页。无需级联事件或类似的东西。只需创建一个自定义控件。 这与用户控件不同。这只是按钮控件的子类。一种更干净的方法。
三个简单的步骤。
注意:我的自定义控件将被称为 HomeButton,我的主页类将被称为 HomePage。除此之外,这对您来说都是开箱即用的。
首先,定义按钮的外观:
<!-- custom home button -->
<Style TargetType="local:HomeButton" BasedOn="{StaticResource BackButtonStyle}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Height="48" Width="48">
<Ellipse Stroke="White" StrokeThickness="2" />
<TextBlock Text="" FontSize="20"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
其次,像这样定义您的自定义控件:
public sealed class HomeButton : Button
{
public HomeButton()
{
this.DefaultStyleKey = this.GetType();
this.Click += HomeButton_Click;
}
void HomeButton_Click(object sender, RoutedEventArgs e)
{
var _Frame = Window.Current.Content as Frame;
var _Type = typeof(HomePage);
_Frame.Navigate(_Type);
}
}
第三,也是最后,将您的主页按钮添加到您的应用中!
<local:HomeButton HorizontalAlignment="Left" VerticalAlignment="Top" Margin="40" />
这是它的样子:
它甚至可以工作! :) 如果您想为按钮设置更多样式,可以很容易地在您的/Common/StandardStyles.xaml 文件中窃取 BackButtonStyle 的样式。然后你可以拥有相同的 View 状态和所有。不管怎样,这会让你到达你想要的地方。
因此,这是解决您在问题中描述的问题的主页按钮。它甚至以一种比您假设您将获得的解决方案问题更少的方式解决它 - 因为跨上下文手动冒泡事件可能会导致噩梦。
希望对您有所帮助。
关于c# - 用户控件上的按钮监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14220164/