Binding Text to Textbox in HubSection - c#

This question is similar to Windows Phone 8.1 Toggling the visibility of a TextBlock in a DataTemplate
and countless others, but none of these ideas are working. The Loaded event is never triggered after I add my Textblock to my datatemplate in my hub. The Visual Tree search is not finding my TextBlock.
I have tried a basic binding like this:
<HubSection Background="{StaticResource HubSectionBackgroundBrush}"
MaxWidth="{x:Bind DesiredHubSectionWidth, Mode=OneWay}"
Header="You have selected:" Padding="60"
>
<DataTemplate x:DataType="local:Scenario4">
<TextBlock TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="{Binding Item}"/>
</DataTemplate>
</HubSection>
with
public string Item { get; set; }
Item = makeText.Text;
But this doesn't work (Text on the Hub is always empty). From looking at previous posts and code I have come up with this xaml code using Dependency Properties:
<HubSection Background="{StaticResource HubSectionBackgroundBrush}"
MaxWidth="{x:Bind DesiredHubSectionWidth, Mode=OneWay}"
Header="You have selected:" Padding="60"
>
<DataTemplate x:DataType="local:Scenario4">
<TextBlock TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="{x:Bind DesiredSelectionText, Mode=OneWay}"/>
</DataTemplate>
</HubSection>
with this in the c#
private static DependencyProperty s_desiredHubSectionWidthProperty
= DependencyProperty.Register("DesiredHubSectionWidth", typeof(double), typeof(Scenario4), new PropertyMetadata(560.0));
private static DependencyProperty selectionText = DependencyProperty.Register("SelectionText", typeof(string), typeof(Scenario4), new PropertyMetadata("Nothing"));
public static DependencyProperty DesiredHubSectionWidthProperty
{
get { return s_desiredHubSectionWidthProperty; }
}
public static DependencyProperty DesiredSelectionTextProperty
{
get { return selectionText; }
}
public string DesiredSelectionText
{
get { return (string)GetValue(selectionText); }
set { SetValue(selectionText, value); }
}
public double DesiredHubSectionWidth
{
get { return (double)GetValue(s_desiredHubSectionWidthProperty); }
set { SetValue(s_desiredHubSectionWidthProperty, value); }
}
and I set the text with
DesiredSelectionText = makeText.Text;
The width binding works perfectly, but the text is not updating. What is the proper way to change Hub/DataTemplate Text at Runtime? Since the Hub is not even printing "Nothing", something must be really wrong.
As a last resort I am thinking I will just construct my own datatemplate and assign it at runtime, but the only code I can find for that is deprecated(uses FrameworkElementFactory).

I was trying to assign to the textblock in the OnNavigatedTo method which is called before the textblock's Loaded method. That's why my program was showing the textblock as null.
Turns out the link I posted is the solution, just for me, the textblock was loaded after the page was navigated to.

Related

Binding in UserControl

I have a UserControl that has an Image and a Textblock, like so:
<Image Stretch="UniformToFill" Source="{Binding Path=ImageURL}"/>
<TextBlock Text="{Binding Path=Title}"/>
in the .cs of the user control i have Dependency properties to make the binding:
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(MyUserControl), null);
public string ImageURL
{
get { return (string)GetValue(ImageURLProperty); }
set { SetValue(ImageURLProperty, value); }
}
public static readonly DependencyProperty ImageURLProperty =
DependencyProperty.Register("ImageURL", typeof(string), typeof(MyUserControl), null);
public MyUserControl()
{
this.InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
In my MainPage.xaml i call it inside a list
<ListView Grid.Row="1"
HorizontalAlignment="Center"
Name="ControlsListView">
<ListView.ItemTemplate>
<DataTemplate>
<controls:MyUserControl Margin="20"
Title="{Binding Title}" //works
ImageURL="{Binding ImageURL}"/> //doesn't work
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And then i get this Data from Json.net and feed it to the ItemsSource of the ListView. It works just for the Title but no for the ImageURL, anyone could help me why?
Probably a bad DataContext, see ReSharper WPF error: "Cannot resolve symbol "MyVariable" due to unknown DataContext". The answer describes how to use the free Snoop utility to detect runtime binding errors.
By default, the DataContext for a UserControl is not set to point at the code behind.
Add this:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
Perhaps the backslashes in your ImageUrl are confusing things.
What ImageUrl are you using? Json might be interpreting the backslash as an escape character, and you might have to encode the ImageUrl using a double backslash.

Databinding of MapControl Center property in Windows Phone 8.1

I'm developing a windows phone 8.1 (winRT) app with MVVM Light and a PCL which use a MapControl.
I'm having an issue with the binding of the MapControl Center property.
At the initialization of the app, the property is set in the ViewModel and the map is correctly centered.
However, when I update the value in the ViewModel, the map is not re-centered but if I bind the value to a textblock it's correctly updated.
XAML :
<Maps:MapControl BorderThickness="2" BorderBrush="Black"
x:Name="Map"
HorizontalAlignment="Right" Margin="0,45,0,0"
VerticalAlignment="Top"
Height="595" Width="400"
ZoomLevel="10"
LandmarksVisible = "False"
TrafficFlowVisible = "False"
PedestrianFeaturesVisible = "False"
Center="{Binding Path=ViewStoreModel.CenterPosition, Mode=OneWay, Converter={StaticResource NormalizedAnchorPointConverter}}"
MapServiceToken="{StaticResource MapServiceTokenString}">
<Maps:MapItemsControl x:Name="MapIcons" ItemsSource="{Binding ViewStoreModel.ListStoreSearch}" >
<Maps:MapItemsControl.ItemTemplate>
<DataTemplate x:Name="Temp" >
<StackPanel Tapped="Image_Tapped" x:Name="MyStack" Maps:MapControl.Location="{Binding store_position, Converter={StaticResource GeoPointConvertCenter}}">
<Image x:Name="PinsImage" Source="ms-appx:///Assets/map-pin-button.png" />
</StackPanel>
</DataTemplate>
</Maps:MapItemsControl.ItemTemplate>
</Maps:MapItemsControl>
</Maps:MapControl>
Property of the ViewModel:
public Location CenterPosition
{
get
{
return _centerPosition;
}
set
{
Set(CenterPositionPropertyName, ref _centerPosition, value);
}
}
public class Location : ObservableObject
{
public const string latitudePropertyName = "latitude";
public const string longitudePropertyName = "longitude";
private double _latitude;
private double _longitude;
public double latitude
{
get
{
return _latitude;
}
set
{
Set(latitudePropertyName, ref _latitude, value);
}
}
public double longitude
{
get
{
return _longitude;
}
set
{
Set(longitudePropertyName, ref _longitude, value);
}
}
The property Center is a type Geopoint so I use a converter to convert it from the custom class Location.
Center is a dependency property so it should be bindable.
Thanks for your help.
I figured out there are some bugs in the MapControl.
The problem comes from the binding mode. OneWay seems to work like OneTime (only at init).
If I put TwoWay it works but the map is updating the ViewModel continuously.
As a workaround, I specified that we have to tell explicity when the XAML has to update the source.
Code:
<Maps:MapControl BorderThickness="2" BorderBrush="Black"
x:Name="Map"
HorizontalAlignment="Right" Margin="0,45,0,0"
VerticalAlignment="Top"
Height="595" Width="400"
ZoomLevel="10"
LandmarksVisible = "False"
TrafficFlowVisible = "False"
PedestrianFeaturesVisible = "False"
Center="{Binding ViewStoreModel.CenterPosition, Mode=TwoWay, UpdateSourceTrigger=Explicit, Converter={StaticResource NormalizedAnchorPointConverter}}"
MapServiceToken="{StaticResource MapServiceTokenString}"
>
We're using a bit of a different approach.
We used the DataContext's PropertyChanged event - in the handler we're checking if e.PropertyName equals CurrentLocation and if it does, I'm calling NearbySitesMap.SetView(currentLocation, ZoomLevel, NearbySitesMap.Heading);.
This way, when CurrentLocation changes, the map gets a nice and smooth animation to the new location.
Have you try to remove "Path" property and bind it directly to your ViewModel?
<Maps:MapControl Center="{Binding ViewStoreModel.CenterPosition, Mode=OneWay, Converter={StaticResource NormalizedAnchorPointConverter}}"/>

Databinding a class with boolean and text to XMAL

I submitted this accidently, I fixed it myself and wasn't going to submit after writing out the question. But have learnt from the comments, thanks!
I am trying to create a simple todo app in win8 and eventually want to hock it into ToDoIst API.
I have created a simple task class to try and get my head around the databinding however I just can not get it to do what I want to do. I have used listboxes and other basic form elements.
task.cs
class task
{
private string content;
private bool complete;
public string Content
{
get {return content;}
set { content = value; }
}
public bool Complete
{
get { return complete; }
set { complete = value; }
}
public task(string content)
{
Content = content;
Complete = false;
}
}
MainPage.xaml
And at the moment my XAML looks like this.
<GridView HorizontalAlignment="Left" Margin="482,190,0,0" VerticalAlignment="Top" Width="400" Height="500">
<ListView x:Name="LVtasks" HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="400" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Content}"/>
<RadioButton/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</GridView>
I have put in some dummy data, 4 elements and when I run it, it comes up with 4 boxes with radio buttons however no text (there is space for the text) I am not sure how I would bind the bool?
I can not see what I am doing wrong. If anyone could help and point me in the right direction, I have searched a fair amount of tutorials and just can not figure it out.
Your code looks a little strange, maybe this is what you want:
<ListView x:Name="LVtasks" HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="400" ItemsSource="{Binding ToDoItems}">
<ListView.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="ToDos" Content="{Binding Content}" IsChecked="{Binding IsComplete}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Do you really want radiobuttons? I think you want Checkboxes, the difference is that when you use radiobuttons only one in a group can be 'checked'
I used this code behind to have a datacontext:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ToDoItems = new ObservableCollection<TodoItem>(new List<TodoItem>
{
new TodoItem("Content1"),
new TodoItem("Content2")
});
this.DataContext = this;
}
public ObservableCollection<TodoItem> ToDoItems { get; set; }
}
I changed the name of task to ToDoItem Task is already a class in the framework and might cause confusion.
For the RadioButton IsChecked is the property to bind to a bool property:
<RadioButton IsChecked="{Binding Path=Complete}"/>
Your text is most likely not showing up because you haven't set up any change notifications and the binding is happening before you set the Content values. Using the INotifyPropertyChanged interface is the most common and usually the easiest way to do this.
Like John already mentioned you should really let the window containing your listview implement the INotifyPropertyChanged interface. And to set the data context of your window like Johan said. It is important that you call the propertychanged method in each setter of a property. It is also useful to use an ObservableCollection as ItemSource of your listview. Try to create an instance of ObservableCollection, create a property for it calling propertychanged method in its setter an set rhe ItemSource of your listview to the property. Do not forget to also call propertychanged whenever you add or remove items from the collection

Binding a property in an ItemsControl ItemTemplate to a DP on the UserControl is not working

A UserControl has 3 Dependency Properties: FormatAvailabilities, Orientation and FullText. FormatAvailabilities is bound to the ItemsSource property of an ItemsControl. Orientation is bound to the Orientation property if the StackPanel which is in the ItemsPanelTemplate within the ItemsControl. FullText is bound to the Visibility property of two TextBlocks inside the DataTemplate of the ItemsControl. I am using two converters to determine which TextBlock to show: a BoolToVisibilityConverter and a BoolToInvertedVisibilityConverter (the latter is an inversion of the former). I copied the Visibility property as-is from the TextBlock (both of them, independently) to the ItemsControl and it works correctly..
It seems that the bindings on the TextBlocks are not working properly because both are always visible. Since they are both binding on the same property but one is inverted, there should never be a possibility for both to be visible at the same time.
I put a breakpoint in my converter and it is never hit, so my guess is that there is an issue with binding from within a repeating control to the outer control in which it is housed.
App.xaml:
<common:BaseApp x:Class="xyz.App" xmlns:converters="clr-namespace:xyz.Converters;assembly=xyz">
<common:BaseApp.RootVisual>
<phone:PhoneApplicationFrame x:Name="RootFrame" Source="/Home.xaml"/>
</common:BaseApp.RootVisual>
<common:BaseApp.Resources>
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
<converters:BoolToVisibilityConverter x:Key="BoolToInvertedVisibilityConverter" IfTrue="Collapsed" IfFalse="Visible"/>
</common:BaseApp.Resources>
</common:BaseApp>
UserControl XAML:
<UserControl
x:Name="FormatsControl"
x:Class="xyz.Formats"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480">
<ItemsControl Background="Transparent" ItemsSource="{Binding ElementName=FormatsControl, Path=FormatAvailabilities}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="{Binding ElementName=FormatsControl, Path=Orientation}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding BindsDirectlyToSource=True}" Margin="0,0,10,0" Visibility="{Binding ElementName=FormatsControl, Path=FullText, Converter={StaticResource BoolToVisibilityConverter}}"/>
<TextBlock Text="{Binding Description}" Margin="0,0,10,0" Visibility="{Binding ElementName=FormatsControl, Path=FullText, Converter={StaticResource BoolToInvertedVisibilityConverter}}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>
UserControl CS:
namespace xyz
{
public partial class Formats : UserControl
{
public static readonly DependencyProperty FormatAvailabilitiesDependencyProperty = DependencyProperty.Register("FormatAvailabilities", typeof(FormatAvailability[]), typeof(Formats), null);
public static readonly DependencyProperty OrientationDependencyProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(Formats), new PropertyMetadata(Orientation.Horizontal));
public static readonly DependencyProperty FullTextDependencyProperty = DependencyProperty.Register("FullText", typeof(bool), typeof(Formats), null);
public FormatAvailability[] FormatAvailabilities
{
get { return (FormatAvailability[])base.GetValue(Formats.FormatAvailabilitiesDependencyProperty); }
set { base.SetValue(Formats.FormatAvailabilitiesDependencyProperty, value); }
}
public Orientation Orientation
{
get { return (Orientation)base.GetValue(Formats.OrientationDependencyProperty); }
set { base.SetValue(Formats.OrientationDependencyProperty, value); }
}
public bool FullText
{
get { return (bool)base.GetValue(Formats.FullTextDependencyProperty); }
set { base.SetValue(Formats.FullTextDependencyProperty, value); }
}
public Formats()
{
InitializeComponent();
}
}
}
I must be over looking something...thanks!
There is an issue with naming UserControls in Silverlight 3 as described by this blog post, which is also present in the Windows Phone 7 version of Silverlight. Effectively, if you give the UserControl a name in the XAML where it is used (i.e. it's parent), then that overrides the name given in the UserControl's own XAML file.
I ran into a similar problem, instead of binding to the elementname I changed the binding to this
Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}
And that works just fine.
Looks like you are missing the OnPropertyChanged handler.
Here is one of my dependency properties. Note the changed handler.
public ObservableCollection<ObjWithDesc> ItemsSource
{
get
{
return (ObservableCollection<ObjWithDesc>)GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
}
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(
"ItemsSource",
typeof(ObservableCollection<ObjWithDesc>),
typeof(HorizontalListBox),
new PropertyMetadata(OnItemsSourcePropertyChanged)
);
static void OnItemsSourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((HorizontalListBox) obj).OnItemsSourcePropertyChanged(e);
}
private void OnItemsSourcePropertyChanged(DependencyPropertyChangedEventArgs e)
{
ObservableCollection<ObjWithDesc> objWithDescList = (ObservableCollection<ObjWithDesc>)e.NewValue;
MainListBox.ItemsSource = objWithDescList;
}

Attach ICommand in WPF UserControl

I implemented a simple button with an image in it:
<Button Command="{Binding ButtonCommand, ElementName=ImageButtonControl}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ButtonImage, ElementName=ImageButtonControl}"/>
<TextBlock Text="{Binding ButtonText, ElementName=ImageButtonControl}" Margin="2,0,0,0"/>
</StackPanel>
</Button>
As you can see, I expose a ButtonCommand property in order to be able to attach an ICommand to this UserControl:
public partial class ImageButton : UserControl
{
/// <summary>
/// The dependency property that gets or sets the source of the image to render.
/// </summary>
public static DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(ImageButton));
public static DependencyProperty TextProperty =
DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton));
public static DependencyProperty ButtonCommandProperty =
DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(ImageButton));
public ImageButton()
{
this.DataContext = this;
InitializeComponent();
}
/// <summary>
/// Gets or sets the button command.
/// </summary>
public ICommand ButtonCommand
{
get { return (ICommand)GetValue(ImageButton.ButtonCommandProperty); }
set { SetValue(ImageButton.ButtonCommandProperty, value); }
}
/// <summary>
/// Gets or sets the button image.
/// </summary>
public ImageSource ButtonImage
{
get { return (ImageSource)GetValue(ImageButton.ImageSourceProperty); }
set { SetValue(ImageButton.ImageSourceProperty, value); }
}
/// <summary>
/// Gets or sets the button text.
/// </summary>
public string ButtonText
{
get { return (string)GetValue(ImageButton.TextProperty); }
set { SetValue(ImageButton.TextProperty, value); }
}
}
Then when I declare my button it gives this:
<uc:ImageButton Grid.Row="1" Grid.Column="0" ButtonCommand="{Binding AttachContextCommand}" ButtonImage="{StaticResource AssociateImage}" ButtonText="Associer"/>
And badaboom, nothing never happen when I click on my ImageButton.
When I replace the ImageButton with a simple button, the ICommand is called.
I even tried to simply extends the Button class and bind an ICommand, but once again, it didn't work...
Help appreciated !
Thx.
You can achieve this in a much cleaner way using a style and a couple of attached properties.
The attached properties will store your specific information.
The style will use these properties and build the look you want.
The element will still be a button so the command and everything else will work.
public class ImageButton
{
public static ImageSource GetImage(DependencyObject obj)
{
return (ImageSource)obj.GetValue(ImageProperty);
}
public static void SetImage(DependencyObject obj, ImageSource value)
{
obj.SetValue(ImageProperty, value);
}
public static readonly DependencyProperty ImageProperty =
DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null));
public static String GetCaption(DependencyObject obj)
{
return (String)obj.GetValue(CaptionProperty);
}
public static void SetCaption(DependencyObject obj, String value)
{
obj.SetValue(CaptionProperty, value);
}
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(ImageButton), new UIPropertyMetadata(null));
}
<Style TargetType="{x:Type Button}"
x:Key="ImageButton">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=(local:ImageButton.Image), RelativeSource={RelativeSource AncestorType={x:Type Button}}}" />
<TextBlock Text="{Binding Path=(local:ImageButton.Caption), RelativeSource={RelativeSource AncestorType={x:Type Button}}}"
Margin="2,0,0,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
You can then use this to declare buttons:
<Button Style="{DynamicResource ImageButton}"
local:ImageButton.Caption="Foo"
local:ImageButton.Image="..." />
Note:
I'm pretty sure it would be cleaner to go through the "Template" property and use a ControlTemplate and TemplateBindings, but that would mean re-creating the border and other stuff around your content, so if you are looking to just define a default "Content", my example would be the way to go, I think.
If the only added functionality that you want for your button is to have an image on it, then I think you're approaching this from the wrong direction. WPF is as awesome as it is because the UI controls are look-less. This means that a Control is merely a definition of functionality + some template to define how it looks. This means that the template can be swapped out at any time to change the look. Also, almost any content can be placed inside of almost any control
For instance, to define a button in your xaml that has the look your going for all you need is this:
<Window ...>
...
<Button Command="{Binding AttachContextCommand}">
<StackPanel Orientation="Horizontal">
<Image Source="{StaticResource AssociateImage}"/>
<TextBlock Text="Associer"/>
</StackPanel>
</Button>
...
</Window>
Just keep in mind that with WPF you don't have to define a new CustomControl or UserControl every time you want to change the look and feel of something. The only time you should need a CustomControl is if you want to add functionality to an existing Control or to create functionality that doesn't exist in any other Control.
Edit Due to comment:
If you're wanting to keep from defining the content for the button every time, the other option is to just have a poco (plain old CLR object) class that would define everything your interested in (I'll write my example as if you're doing this for a tool bar, because it makes sense to me):
public class ToolBarItem : INotifyPropertyChanged
{
public string Text { get ... set ... }
public ICommand Command { get ... set ... }
public ImageSource Image { get ... set ... }
}
That has a data template defined somewhere (App.xaml, Window.Resources, etc):
<DataTemplate DataType="{x:Type l:ToolBarItem}">
<Button Command="{Binding Command}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</Button>
</DataTemplate>
And then use the guy in your xaml like this:
<Window ...>
...
<ContentControl>
<ContentControl.Content>
<l:ToolBarItem Image="..." Command="..." Text="..."/>
</ContentControl.Content>
</ContentControl>
...
</Window>
I just don't know that the way you're trying to do it is the most WPF way you could do it.
EDIT Updated based on second comment
Sorry, I forgot to include the ContentControl surrounding that. Now that I remembered that, I realize that that's not much less verbose than the original where you are specifying the content manually. I'll post a new answer to help with your original question.
To re-answer the original question:
What I think you want to do is create a new CustomControl called ImageButton. Then change it to extend from Button instead of Control. You won't need a Command property since Button already has one. You'll only need to add an Image property and you can reuse the Content property from button instead of having a Text property.
When your CustomControl is created, it'll add an entry in your Generic.xaml for the default style of your ImageButton. In the Setter for the Template property you can change the ControlTemplate to this:
<ControlTemplate TargetType="{x:Type local:ImageButton}">
<StackPanel Orientation="Horizontal">
<Image Source="{TemplateBinding Image}"/>
<ContentPresenter/>
</StackPanel>
</ControlTemplate>
Then, again, when you want to use it:
<Window ... >
...
<l:ImageButton Image="{StaticResource ...}" Command="...">
Associer
</l:ImageButton>
...
</Window>
The built-in WPF button contains code that fires the attached command in response to being clicked. Your "ImageButton" derives from UserControl, so you don't get that behavior. Probably the shortest route to get what you want is for your ImageButton class to actually derive from the WPF Button class. To accomplish that, change the markup for ImageButton from
<UserControl
...
>
...
</UserControl>
to
<Button
...
>
...
</Button>
Then change the base class of ImageButton from UserControl to Button.
You'll probably need to make some other minor changes before it all works.

Categories

Resources