Reputation: 4534
I've done a WPF base usercontrol for all my usercontrols to inherit of. In this base usercontrol class, I want to have a button associated to a click event. I've made it like this :
public class MBaseUserControl : UserControl
{
//[...]
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
StackPanel mainPanel = new StackPanel();
EditButton = new Button();
EditButton.Height = EditButton.Width = 24;
EditButton.MouseEnter += EditButton_MouseEnter;
EditButton.MouseLeave += EditButton_MouseLeave;
EditButton.Click += new RoutedEventHandler(EditButton_Click);
EditButton.Background = Brushes.Transparent;
EditButton.BorderBrush = Brushes.Transparent;
EditButton.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
EditButton.VerticalAlignment = System.Windows.VerticalAlignment.Top;
StackPanel buttonPanel = new StackPanel();
Image editButtonImage = ImageTools.ConvertDrawingImageToWPFImage(Properties.Resources.edit, 24, 24);
buttonPanel.Children.Add(editButtonImage);
EditButton.Content = buttonPanel;
mainPanel.Children.Add(EditButton);
//Add this to new control
((IAddChild)newContent).AddChild(mainPanel);
SetCMSMode(false);
}
}
But when I click the button on GUI, nothing is firing (neither Mouse events or click event). What did I miss ?
Thanks by advance !
Upvotes: 1
Views: 756
Reputation: 21979
You can try to template UserControl
to have its Content
shown inside some other content. Note, it's untested, but I think it should work.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:DemoUni">
<ControlTemplate x:Key="SomeKey" TargetType="UserControl">
<Grid x:Name="PART_Grid">
<ContentPresenter x:Name="PART_Content" Content="{Binding}"/>
<!-- ... some other content -->
</Grid>
</ControlTemplate>
</ResourceDictionary>
In constructor of UserControl
var dictionary = new ResourceDictionary();
// xaml containing control template
dictionary.Source = new Uri("/ProjectName;component/MyUserControlTemplate.xaml", UriKind.Relative);
Template = dictionary["SomeKey"] as ControlTemplate;
To access other content (Grid
as example)
private Grid _partGrid;
private Grid PartGrid
{
get
{
if (_partGrid == null)
_partGrid = (Grid)Template.FindName("PART_Grid", this);
return _partGrid;
}
}
The little drawback is what you can not access PARTs in constructor, so that you have to use Loaded
of UserControl
to wire up events (subscribe to Loaded
in constructor, subscribe to button events in Loaded
).
Upvotes: 1
Reputation: 133
perhaps adding new MouseEventHandler to your code:
EditButton.MouseEnter += new MouseEventHandler(EditButton_MouseEnter);
EditButton.MouseLeave += new MouseEventHandler(EditButton_MouseLeave);
Upvotes: 0