G G*_* Gr 6 c# wpf xaml user-controls
当你在wpf中有一个usercontrol时,它可以到达其父元素的外部吗?例如,我的用户控件只列出了控件内部的一些通用的东西,它们被封装在主窗口的dockpanel中,但是我在主窗口中有一个文本框和按钮,我想从控件中访问...这可能吗?
这将节省我很多时间,而不是改变整个窗口的内容,并在每个用户控件中显示相同的文本框/按钮.如果有人有这方面的例子,我将不胜感激.
是的,这是可能的,这是我用来从具有 DP 的 UserControl 中编写演示文稿的一些代码。
我一点也不喜欢它,但它确实有效。我也认为这是一个很棒的主题,也许一些代码将有助于获得更好的答案!
干杯,
贝瑞
<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>
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)

<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>
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
2594 次 |
| 最近记录: |