How do I bind a different DataContext for my UserControl? - c#

So I have an application that's setup like this.
my MainView.xaml
<ItemsControl ItemsSource="{Binding CardViewModel.Users}"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True"
dd:DragDrop.UseDefaultEffectDataTemplate="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:UserCard/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And the ViewModel
class BaseViewModel : ObservableObject
{
public CardViewModel CardViewModel { get; set; } = new CardViewModel();
}
This works fine it displays two UserCards which is my UserControl in the ItemsControl which is exactly what it should be doing and it also binds the Text properties to what it needs to.
<Grid Style="{StaticResource UserCardStyle}">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit"/>
<MenuItem Header="Remove"
Command="{Binding BaseViewModel.CardViewModel.command}"/>
</ContextMenu>
</Grid.ContextMenu>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="75"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Width="75"
HorizontalAlignment="Left"
Column="0">
<Ellipse Width="50"
Height="50"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="10">
<Ellipse.Fill>
<ImageBrush ImageSource="{Binding Avatar}"/>
</Ellipse.Fill>
</Ellipse>
</Grid>
<Grid Column="1">
<TextBlock Text="{Binding Description}"
TextWrapping="Wrap"
Width="180"
VerticalAlignment="Top"
Margin="10"
FontFamily="Consolas"/>
<TextBlock Width="100"
Height="20"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Margin="5"
Text="{Binding Name}"
FontFamily="Consolas"/>
<TextBlock Width="100"
Height="20"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"
Text="{Binding Id}"
FontFamily="Consolas"/>
</Grid>
</Grid>
However I wanted to add a DataContext as you can see at the top but I have no idea how to bind the DataContext of the UserControl to something else so that I can create commands for the ContextMenu MenuItems
I did setup a RelayCommand that works on the ViewModel because I have the DataContext set properly there.
Right now the UserCard datacontext inherits from it's parent in the MainWindow view which makes it to where the DataContext for the properties are all from User
public class User : ObservableObject
{
public ImageSource Avatar { get; set; }
public string Description { get; set; }
public int Id { get; set; }
}
I want to be able to either create a ViewModel for that specific control and add commands to that or so that I can bind it to the CardViewModel and still display the data from the Users collection
public CardViewModel()
{
/*
* Commands
*/
command = new RelayCommand(o => LoadImage(), o => true);
AddUser = new RelayCommand(u => DisplayUserBuilder(), u => true);
Users = new ObservableCollection<User>();
Users.Add(new User
{
Name = "User",
Description = "A description",
Id = 0
});
Users.Add(new User
{
Name = "User1",
Description = "Super nice description",
Id = 1
});
If I set the DataContext in the CodeBehind like this, the command works fine but then I can't see any text
public partial class UserCard : UserControl
{
public UserCard()
{
InitializeComponent();
this.DataContext = new BaseViewModel();
}
}

I believe you need something like this :
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit"/>
<MenuItem Header="Remove"
Command="{Binding DataContext.CardViewModel.command, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MainView}}"/>
</ContextMenu>
</Grid.ContextMenu>

This is what I ended up doing, adding a reference to the ViewModel and then setting it.
<Grid.ContextMenu>
<ContextMenu >
<ContextMenu.DataContext>
<dad:BaseViewModel/>
</ContextMenu.DataContext>
<MenuItem Header="Edit"/>
<MenuItem Header="Remove"
Command="{Binding CardViewModel.command}"/>
</ContextMenu>
</Grid.ContextMenu>
If someone knows a "better" or "cleaner" way of doing the same thing please let me know since I am trying to develop as a developer, no pun intended.

Related

How to use selected items from a listview in multiple views

I have a separate view that contains an observable collection and would like to use the selected item from the collection in another view (MainView). Can anyone tell me how to implement the property change in the MainView?
The Main Window:
<Window.DataContext>
<local:MainWindowViewModel x:Name="mainWindowViewModel"/>
</Window.DataContext>
<Window.Resources>
<view:OwnerListViewModel x:Key="OwnerList"/>
</Window.Resources>
<TextBlock Height="25" Margin="0 5 0 0" Grid.Row="1" Grid.Column="0" Text="{Binding
PersonModel.FirstName}" ></TextBlock>
<TextBlock Height="25" Margin="0 5 0 0" Grid.Row="1" Grid.Column="1" Text="{Binding
PersonModel.SurName}" Grid.ColumnSpan="2"></TextBlock>
In MainWindowViewModel:
private OwnerListViewModel OwnerListViewModel { get; } = new OwnerListViewModel();
public Owner PersonModel
{
get { return OwnerListViewModel.PersonModel; }
set { OwnerListViewModel.PersonModel = value; OnPropertyChanged(); }
}
In the LoadOwner Window, i created the ListView:
<Window.DataContext>
<view:OwnerListViewModel/>
</Window.DataContext>
<ListView Grid.Column="0" ItemsSource="{Binding PersonsView}" SelectedValue="{Binding
PersonModel, Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCmd}"
CommandParameter="{Binding
ElementName=PersonListWindow}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="auto">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="0 0 5 0" VerticalAlignment="Center"
Text="{Binding FirstName}"/>
<TextBlock Grid.Column="1" VerticalAlignment="Center"
Text="{Binding SurName}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
My OwnerListViewModel:
Here I am not sure how to implement the property change. Using an asynchronous task, or are there other options? I would be very grateful for a tip!
public OwnerListViewModel()
{
Persons = new ObservableCollection<Owner>();
var sample1 = new Owner()
{
FirstName = "SampleFirstName1",
SurName = "SampleLastname1",
Street = "SampleStreet1",
HouseNumber = 987,
AdditionalAdress = "",
ZipCode = 99999,
City = "SampleCity1"
};
AddOwner(sample1);
PersonsView = CollectionViewSource.GetDefaultView(Persons);
PersonsView.CurrentChanged += (s, e) =>
{
OnPropertyChanged(() => PersonModel);
};
SelectionChangedCmd = new RelayCommand<Window>(this.closeWindow);
}
#region listProperties
private ObservableCollection<Owner> Persons { get; }
public ICollectionView PersonsView { get; set; }
public Owner PersonModel
{
get => PersonsView.CurrentItem as Owner;
set
{
PersonsView.MoveCurrentTo(value);
OnPropertyChanged();
}
}
You created different objects of OwnerListViewModel. One way is deleting this code from 2 views:
<Window.Resources>
<view:OwnerListViewModel x:Key="OwnerList"/>
</Window.Resources>
and bind datacontext in view codebehind:
var ownerListViewModel = new OwnerListViewModel();
LoadOwnerWindow.DataContext = ownerListViewModel;
MainView.DataContext = ownerListViewModel.PersonModel;
Also you can use IoC to bind view models.
Also, the other way is using WPF messenger to send changed owner as a message from LoadOwnerWindow to MainView
the solution is to set the data context directly in the main window:
<TextBox Height="25" Margin="0 5 0 0" Grid.Row="1" Grid.Column="0" DataContext="{Binding OwnerListViewModel.SelectedItem}" Text="{Binding FirstName}" ></TextBox>
<TextBox Height="25" Margin="0 5 0 0" Grid.Row="1" Grid.Column="1" DataContext="{Binding OwnerListViewModel.SelectedItem}" Text="{Binding SurName}" Grid.ColumnSpan="2"></TextBox>

Dynamic textbox binding to a list

I am very new to MVVM and I am stuck with data binding. I have a button on my view page which dynamically creates text boxes but I cannot see how I bind these textboxes to my List in ViewModel.
In my view i have:
<Button x:Name="btWebsite" Grid.ColumnSpan="2" Width="50" Height="50" Click="btWebsite_Click" Margin="23,245,259,202">
<StackPanel x:Name="pnWebsiteButton" Orientation="Horizontal">
<Image x:Name="imgWebsite" Source= "Images/webIcon.jpg" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
</Button>
<GroupBox x:Name="grpWebsite" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="73,245,0,0" Grid.ColumnSpan="2" Height="51" Width="170" BorderBrush="{x:Null}" BorderThickness="0">
<ScrollViewer x:Name="pnScrollWebsite" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Margin="0,0,0,-6">
<StackPanel x:Name="pnWebsite" Orientation="Vertical" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="1,2,0,0" VerticalAlignment="Top" IsEnabled="True">
</StackPanel>
</ScrollViewer>
</GroupBox>
The code behind the button is:
private void btWebsite_Click(object sender, RoutedEventArgs e)
{
var newTextBox = new TextBox();
newTextBox.Text = "type the website address...";
newTextBox.Foreground = Brushes.Gray;
newTextBox.Width = 150;
newTextBox.Name = "txtWebsite" + iWebsites;
pnWebsite.Children.Add(newTextBox);
pnWebsite.RegisterName(newTextBox.Name, newTextBox);
iWebsites++;
}
In my ViewModel i have:
public List<string> Websites
{
get { return _websites; }
set
{
if (value != _websites)
{
_websites = value;
OnPropertyChanged("Websites");
}
}
}
I am struggling to see how I get the website textboxes into the viewmodel list. Thank you for your help
Delete your event handler from the code-behind: btWebsite_Click.
Modify your xaml like this:
<Button x:Name="btWebsite" Grid.ColumnSpan="2" Width="50" Height="50" Command="{Binding AddNewStringCommand}" Margin="23,245,259,202">
<StackPanel x:Name="pnWebsiteButton" Orientation="Horizontal">
<Image x:Name="imgWebsite" Source= "Images/webIcon.jpg" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
</Button>
<GroupBox x:Name="grpWebsite" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="73,245,0,0" Grid.ColumnSpan="2" Height="51" Width="170" BorderBrush="{x:Null}" BorderThickness="0">
<ScrollViewer x:Name="pnScrollWebsite" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Margin="0,0,0,-6">
<StackPanel x:Name="pnWebsite" Orientation="Vertical" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="1,2,0,0" VerticalAlignment="Top" IsEnabled="True">
<ItemsControl ItemsSource="{Binding Websites}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Mode=TwoWay}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</ScrollViewer>
</GroupBox>
You need to modify your ViewModel also:
public ObservableCollection<string> Websites { get; set; }
public ICommand AddNewStringCommand => new RelayCommand(AddNewString);
private void AddNewString()
{
Websites.Add(string.Empty);
}
Instead of RelayCommand you can use any implementation of ICommand. I use for example MVVMLight.
As you see, the main differences:
Instead of handling the Click event, there is a Command Binding in
the button.
Instead of generating new controls from code behind, there is an
ItemsControl that creates one every time when we have a new
element in the collection.
The new TextBox's Text property is bound to the new element.
Update:
I made a mistake, ObservableCollection is not working directly with the TextBox.
It seems you need something in addition:
public class Website
{
public string Name { get; set; }
}
Modify the ViewModel like this:
public ObservableCollection<Website> Websites { get; set; } = new ObservableCollection<Website>();
public ICommand AddNewStringCommand => new RelayCommand(AddNewString);
private void AddNewString()
{
Websites.Add(new Website {Name = "new website"});
}
And the ItemsTemplate like this:
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel >
<TextBox Text="{Binding Name, Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>

MenuItem binding datacontext in listview

I have a ListView with a DataTemplate, inside this templates there are several textblocks and a button. The button has a contextmenu with fixed items. The binding of the listviewitems works fine, but binding a property to the contextmenu does not seem to work.
<ListView x:Name="lv_clients" Margin="0 22 0 0" SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid Grid.Column="0" Grid.RowSpan="2" Background="{Binding StateColor}">
</Grid>
<TextBlock Grid.Column="1" Text="{Binding DisplayString}" Foreground="Black" Height="20" FontWeight="Bold" Padding="2,2,0,0" />
<Button Click="Button_ListItem_Click" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Top">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Anrufen" Name="mn_call" Click="mn_call_Click" DataContext={Binding Number} />
</ContextMenu>
</Button.ContextMenu> ...</Button>
<StackPanel Grid.Column="1" Grid.Row="1">
<TextBlock Text="{Binding State}" Height="20" Padding="2,2,0,0"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstEntry.KDKGRS}" Height="20" FontWeight="Bold" Padding="2,2,2,0" HorizontalAlignment="Left" Foreground="{Binding FirstEntry.ConvertedKGFARBE}" />
<TextBlock Text="{Binding FirstEntry.ADNAMI}" Height="20" Padding="0,2,0,0" HorizontalAlignment="Left" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I have removed some unnecessary bits of the code (style and columndefinitions) for readability.
The important part is the MenuItem inside the Button. My underlying class has a public string property Number. This should be passed to the menu item. But the DataContext of the MenuItem is always null inside the click event.
I've read something about the contextmenu not beeing part of the visual tree, but I can't wrap my head around it. Could somebody explain the issue with the binding?
Edit Code for the underlying class:
Again removed some unnecessary code for the question
public class PhoneClient
{
public String Name { get; set; }
public String Number { get; set; }
public String Extension { get; set; }
public String DisplayString
{
get
{
return String.IsNullOrEmpty(Name) ? Number : String.Format("{0} ({1})", Name, Extension);
}
}
}
And the binding of the ListBox:
List<PhoneClient> clients = new List<PhoneClient>();
clients = load(); //returns active Clients
lv_clients.ItemsSource = clients;
Bridging the gap
<ContextMenu Tag="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Anrufen" Click="mn_call_Click" Name="mn_call"
DataContext="{Binding Tag.Number, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
</ContextMenu>
Handler
private void mn_call_Click(object sender, RoutedEventArgs e)
{
MenuItem currentMenuItem = (MenuItem)sender;
string number = (string)currentMenuItem.DataContext;
// Do Stuff
}
EDIT
MainWindow.xaml
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Margin="10">
<ListView x:Name="lv_clients" Margin="0 22 0 0" SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="LightGray" Width="100">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Background="LightGreen">
</Grid>
<TextBlock Text="{Binding DisplayString}" Foreground="Black" Height="20" FontWeight="Bold" Padding="2,2,0,0" />
<Button Click="Button_ListItem_Click" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Top">
<Button.ContextMenu>
<ContextMenu Tag="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Show" Click="mn_call_Click" Name="mn_call" DataContext="{Binding Tag.Number, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
</ContextMenu>
</Button.ContextMenu> ...
</Button>
<StackPanel Grid.Row="1">
<TextBlock Text="{Binding State}" Height="20" Padding="2,2,0,0"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Foo" Height="20" FontWeight="Bold" Padding="2,2,2,0" HorizontalAlignment="Left" Foreground="Blue" />
<TextBlock Text="Bar" Height="20" Padding="0,2,0,0" HorizontalAlignment="Left" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<PhoneClient> clients = new List<PhoneClient>();
clients.Add(new PhoneClient() { Name = "Kumar", Number = "0101010", Extension = "555", State = "New York" });
clients.Add(new PhoneClient() { Name = "Shanaya", Number = "1010101", Extension = "555", State = "New Jersey" });
clients.Add(new PhoneClient() { Name = "Billy Bob", Number = "6543210", Extension = "555", State = "Single" });
lv_clients.ItemsSource = clients;
}
public class PhoneClient
{
public String Name { get; set; }
public String Number { get; set; }
public String Extension { get; set; }
public String State { get; set; }
public String DisplayString
{
get
{
return String.IsNullOrEmpty(Name) ? Number : String.Format("{0} ({1})", Name, Extension);
}
}
}
private void mn_call_Click(object sender, RoutedEventArgs e)
{
MenuItem currentMenuItem = (MenuItem)sender;
string number = (string)currentMenuItem.DataContext;
MessageBox.Show("Number " + number);
}
private void Button_ListItem_Click(object sender, RoutedEventArgs e)
{
Button currentButton = (Button)sender;
PhoneClient data = (PhoneClient)currentButton.DataContext;
MessageBox.Show(data.Name + " tapped");
}
}
}

Binding to a Command from a DataTemplate in WPF

firstly thanks in advance for any help.
I have an application that i want to add a Navigation menu into. I have created a DataTemplate that has all my buttons and styling and I currently have that in my stylesheet.
<DataTemplate x:Key="Navigation">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="4*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<UniformGrid Grid.Row="0" Columns="1">
<Button Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Style="{StaticResource MenuButtonStyle}" >Page 1</Button>
<Button Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Style="{StaticResource MenuButtonStyle}" >Page 2</Button>
<Button Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Style="{StaticResource MenuButtonStyle}" >Page 3</Button>
<Button Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Style="{StaticResource MenuButtonStyle}" >Page 4</Button>
</UniformGrid>
<ToggleButton Grid.Row="1" Style="{StaticResource ToggleBtnToolStyle}" x:Name="Menu" IsChecked="true" Background="Transparent" BorderThickness="0" >
<StackPanel Orientation="Horizontal">
<ContentPresenter Margin="5" Height="50" Content="{StaticResource MenuIcon}"></ContentPresenter>
<Viewbox>
<TextBlock Margin="5" Style="{StaticResource TxtToolStyle}">Menu</TextBlock>
</Viewbox>
</StackPanel>
</ToggleButton>
</Grid>
</DataTemplate>
Currently the only way i have been able to get this working is to remove it from the DataTemplate and implement the grid on each page.
Is there a way of binding to my NavigationViewModel from my DataTemplate that is stored in my Stylesheet?
I'm sorry if this question is badly worded, I'm new to WPF and can do the basic data binding but I'm lost here.
Thanks
Edit
The ViewModel with the Commands i would like to link to looks like this
public abstract class NavigationViewModelBase : ViewModelBase
{
private List<DicomMetadataModel> _dicomMetadata;
//Navigation Cmd
public ICommand AcquisitionPageCmd { get; private set; }
public ICommand ManualEntryWindowCmd { get; private set; }
public ICommand SessionWindowCmd { get; private set; }
public ICommand SettingsWindowCmd { get; private set; }
public ICommand StudyInfoPageCommandCmd { get; private set; }
public ICommand ViewerPageCmd { get; private set; }
public ICommand WorklistPageCmd { get; private set; }
protected NavigationViewModelBase()
{
AcquisitionPageCmd = new RelayCommand(() => Messenger.Default.Send(new GoToPageMessage(Pages.AcquisitionScreen)));
ManualEntryWindowCmd = new RelayCommand(() => Messenger.Default.Send(new ShowDialogMessage(Pages.ManualEntry, DicomMetadata)));
SessionWindowCmd = new RelayCommand(() => Messenger.Default.Send(new ShowDialogMessage(Pages.Session)));
SettingsWindowCmd = new RelayCommand(() => Messenger.Default.Send(new ShowDialogMessage(Pages.Settings)));
ViewerPageCmd = new RelayCommand(() => Messenger.Default.Send(new GoToPageMessage(Pages.Viewer)));
WorklistPageCmd = new RelayCommand(() => Messenger.Default.Send(new GoToPageMessage(Pages.Worklist)));
}
}
}
And them in every page i would like to add the Navigation Menu into the code will look like this
<ContentControl Grid.Column="2" Grid.Row="2" Content="{Binding}" ContentTemplate="{StaticResource Navigation }" />

Dynamic MenuItems with ItemsSource in xaml?

I'm crap atn english, so sorry..
I'm trying to create dynamic menu items that display something based on a collection (a list of object), here is my xaml, you can see the "ListBox" and the "MenuItem".
As I said, I'm binding the header to the "name" of my object :
MainWindow.xaml
<Grid Margin="0,0,-8,-9" Background="Black" >
<DockPanel x:Name="LayoutRoot">
<Grid VerticalAlignment="Top">
<MediaElement x:Name="mediaElement" HorizontalAlignment="Center" Margin="0,0,60,30" VerticalAlignment="Top" MouseLeftButtonUp="mediaElement_MouseLeftButtonUp">
</MediaElement>
<Menu HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="525" IsMainMenu="True">
<MenuItem Header="Menu">
<ListBox x:Name="myList" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="461,-261,-1,106" Background="#FFFFE800" MouseDoubleClick="ListBox_Double_Click" Width="57">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<MenuItem Header="{Binding name}"> </MenuItem>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</MenuItem>
</Menu>
</Grid>
Here is my code in the c#, as you can see I bind "myList" (which is my ListBox) with the ItemsGetSource of list (which contains the things I want to display in my menu):
public MainWindow()
{
var list = new List<History>
{
new History() { name = "Guy1"},
new History() { name = "Guy2"},
new History() { name = "Guy3"},
new History() { name = "Guy4"},
};
InitializeComponent();
this.myList.ItemsSource = list;
}
And my class "History" (the "name" field is what I want to display)
namespace MediaPlayer
{
public class History
{
// "prop" puis "tab"
public String name { get; set; }
public String path { get; set; }
public int time { get; set; }
public override string ToString()
{
return name;
}
}
}
I think I can't use itemSource for my menuItems, maybe?
Here is an example that only uses MenuItems:
MainWindow.xaml
<Grid Margin="0,0,-8,-9" Background="Black" >
<DockPanel x:Name="LayoutRoot">
<Grid VerticalAlignment="Top">
<MediaElement x:Name="mediaElement" HorizontalAlignment="Center" Margin="0,0,60,30" VerticalAlignment="Top" MouseLeftButtonUp="mediaElement_MouseLeftButtonUp">
</MediaElement>
<Menu HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="525" IsMainMenu="True">
<MenuItem Header="Menu" x:Name="myList">
<MenuItem.ItemContainerStyle>
<Style>
<Setter Property="MenuItem.Header" Value="{Binding name}"/>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
</Menu>
</Grid>
</DockPanel>
</Grid>
The result looks like this:

Categories

Resources