当您在 wpf 中有一个用户控件时,它可以到达其父元素之外吗?例如,我的用户控件只是列出了一些通用的东西,这些东西保存在控件中,这些控件封装在主窗口的停靠面板中,但我在主窗口中有一个文本框和按钮,我想从控件中访问它们......这可能吗?
这将节省我很多时间,而不是更改整个窗口的内容并在每个用户控件中显示相同的文本框/按钮。如果有人有这方面的例子,将不胜感激。
是的,这是可能的,这里是一些我用来从具有 DP 的 UserControls 组成演示文稿的代码。
我一点也不喜欢它,但它确实有效。我也认为这是一个很棒的话题,也许一些代码将有助于获得更好的答案!
干杯, 贝瑞
<Button x:Name="btnAddNewItem" Style="{StaticResource blueButtonStyle}" > <StackPanel Orientation="Horizontal"> <Image Source="{resx:Resx ResxName=Core.Presentation.Resources.MasterDetail, Key=bullet_add}" Stretch="Uniform" /> <Label x:Name="tbItemName" Margin="5" Foreground="White" Padding="10, 0">_Add New [item]</Label> </StackPanel> </Button>
public partial class AddNewItemButton : UserControl { ... #region Item Name public static readonly DependencyProperty ItemNameProperty = DependencyProperty.Register( "ItemName", typeof(string), typeof(AddNewItemButton), new FrameworkPropertyMetadata(OnItemNameChanged)); public string ItemName { get { return (string)GetValue(ItemNameProperty); } set { SetValue(ItemNameProperty, value); } } public string ButtonText { get { return (string) tbItemName.Content; } } private static void OnItemNameChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { // When the item name changes, set the text of the item name var control = (AddNewItemButton)obj; control.tbItemName.Content = string.Format(GlobalCommandStrings.Subject_Add, control.ItemName.Capitalize()); control.ToolTip = string.Format(GlobalCommandStrings.Subject_Add_ToolTip, control.ItemName); } #endregion #region Command public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( "Command", typeof(ICommand), typeof(AddNewItemButton), new FrameworkPropertyMetadata(OnCommandChanged)); public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } private static void OnCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { // When the item name changes, set the text of the item name var control = (AddNewItemButton)obj; control.btnAddNewItem.Command = control.Command; } #endregion }
<UserControl ... xmlns:uc="clr-namespace:Smack.Core.Presentation.Wpf.Controls.UserControls" > <DockPanel LastChildFill="True"> ... <uc:AddNewItemButton x:Name="_addNewItemButton" Margin="0,0,10 0" DockPanel.Dock="Right" /> ... </DockPanel> </UserControl>