加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用wpf中的父元素的UserControl?

发布时间:2020-12-15 08:20:33 所属栏目:百科 来源:网络整理
导读:当你在wpf中有一个usercontrol时,它可以到达其父元素的外部吗?例如,我的用户控件只列出了控件内部的一些通用的东西,它们被封装在主窗口的dockpanel中,但是我在主窗口中有一个文本框和按钮,我想从控件中访问…这可能吗? 这将节省我很多时间,而不是改变整个
当你在wpf中有一个usercontrol时,它可以到达其父元素的外部吗?例如,我的用户控件只列出了控件内部的一些通用的东西,它们被封装在主窗口的dockpanel中,但是我在主窗口中有一个文本框和按钮,我想从控件中访问…这可能吗?

这将节省我很多时间,而不是改变整个窗口的内容,并在每个用户控件中显示相同的文本框/按钮.如果有人有这方面的例子,我将不胜感激.

解决方法

是的,这是可能的,这里有一些我用来编写具有DP的UserControl演示文稿的代码.

我甚至不爱它,但它确实有效.我也认为这是一个很棒的主题,也许一些代码可以帮助我们找到更好的答案!

干杯,
浆果

UserControl XAML

<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>

UserControl代码背后

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),new FrameworkPropertyMetadata(OnCommandChanged));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty,value); }
    }

    private static void OnCommandChanged(DependencyObject obj,set the text of the item name
        var control = (AddNewItemButton)obj;
        control.btnAddNewItem.Command = control.Command;
    }

    #endregion

}

另一个显示组合的UserControl

<UserControl ...
         xmlns:uc="clr-namespace:Smack.Core.Presentation.Wpf.Controls.UserControls" 
         >

    <DockPanel LastChildFill="True">
        ...
        <uc:AddNewItemButton x:Name="_addNewItemButton" Margin="0,10 0" DockPanel.Dock="Right"  />
        ...
    </DockPanel>
</UserControl>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读