How can I use DelegateCommand correctly? - c#

In the debug mode, goes from constructor to the set method, but in the get method does not enter at any point, which I think is the problem, but I don't know how to solved.
In the .xaml file I defined the button.
<dx:ThemedWindow
x:Class="ProductsModule.View.ProductView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
Title="MenuView" Height="800" Width="1000">
<Grid Margin="20" VerticalAlignment="Top" Background="White" Height="420" DataContext="{Binding Detail}">
<Grid.Effect>
<DropShadowEffect BlurRadius="20" ShadowDepth="1"/>
</Grid.Effect>
<StackPanel Margin="750 70 70 70" HorizontalAlignment="Left">
<TextBlock Text="{Binding Name}" FontSize="18" Margin="0 5" Foreground="#FF6A6A6A"/>
<Button Command="{Binding ShowCommand }">Add data</Button>
</StackPanel>
</Grid>
</dx:ThemedWindow>
In .xaml.cs file I defined datacontext.
public SecondView()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
VIEW MODEL
public ViewModel()
{
ShowCommand = new DelegateCommand(ShowMethod);
}
public ICommand ShowCommand
{
get;
set;
}
private void ShowMethod()
{
OrderView orderView = new OrderView();
orderView.Show();
}
When I press the button, ShowMethod() is not called and does not do anything.

Related

wpf xaml MVVM inheritance with multiple ContentPresenter

I am rewriting import masks that have a lot in common, so I want (and must) use inheritance.
I have a basic UserControl with all common controls: (I have left out the grid definitions)
BaseClass.xaml
<UserControl x:Class="BaseImport.BaseClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Grid>
<Border Grid.Row="0" Grid.Column="0">
<StackPanel>
<Label Content="Text1:"/>
<ComboBox Name="cbText1" MinWidth="80"/>
</StackPanel>
</Border>
<Border Grid.Row="0" Grid.Column="1">
<StackPanel>
<Label Content="Text2:"/>
<ComboBox Name="cbText2" MinWidth="80"/>
</StackPanel>
</Border>
<Border Grid.Row="0" Grid.Column="2">
<StackPanel>
<ContentPresenter ContentSource="Content"/> <!-- ContentSource="Content" is the default-->
</StackPanel>
</Border>
<!-- next Row -->
<Border Grid.Row="1" Grid.Column="0">
<StackPanel>
<Label Content="Text3:"/>
<TextBox Name="tbText3" TextWrapping="Wrap" Text="" MinWidth="80" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Grid.Row="1" Grid.Column="1">
<StackPanel>
<ContentPresenter/>
</StackPanel>
</Border>
</Grid>
</ControlTemplate>
</UserControl.Template>
</UserControl>
This is a kind of Template that gets "used" like this:
MainWindow.xaml (just for demonstration a mainwindow)
<Window x:Class="zzz.MainWindow"
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"
xmlns:my="clr-namespace:BaseImport;assembly=BaseImport"
mc:Ignorable="d"
Title="MainWindow" Height="280" Width="600">
<my:BaseClass>
<StackPanel>
<Label Content="Test:"/>
<ComboBox ItemsSource="{Binding TestTyps}" MinWidth="80"/>
</StackPanel>
</my:BaseClass>
</Window>
MainWindow.xaml.cs
using WpfApp1.ViewModel;
namespace zzz
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
}
and to wrap it up MainViewModel.cs:
namespace WpfApp1.ViewModel
{
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public string[] TestTyps { get { return new string[] { "abc", "123", "xyz" }; } }
}
}
If I have one ContentPresenter everything works fine. But in the BaseClass I have two, potentially more.
Like this only the "last" Presenter gets populated. And in MainWindow.xaml can only be one declared.
How can I put more Content in MainWindow.xaml?
How can I select the right one?
Thanks
The red rectangle is were the second presenter is located (row 1, column 1) but I want it to be were the arrow points (row 0, column 2).
I want another control in place of the red rectangle also declared in MainWindow.xaml.
The stuff you put directly in the <my:BaseClass> tags is the contentProperty which can be only one.
Why only the last ContentPresenter shows it? Because each VisualElement can only have one parent, so the last one claiming it wins.
However you can create as many properties as you want.
<UserControl x:Class="BaseImport.BaseClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Grid>
<Border Grid.Row="0" Grid.Column="0">
<StackPanel>
<Label Content="Text1:"/>
<ComboBox Name="cbText1" MinWidth="80"/>
</StackPanel>
</Border>
<Border Grid.Row="0" Grid.Column="1">
<StackPanel>
<Label Content="Text2:"/>
<ComboBox Name="cbText2" MinWidth="80"/>
</StackPanel>
</Border>
<Border Grid.Row="0" Grid.Column="2">
<StackPanel>
<ContentPresenter ContentSource="FirstContent"/>
</StackPanel>
</Border>
<!-- next Row -->
<Border Grid.Row="1" Grid.Column="0">
<StackPanel>
<Label Content="Text3:"/>
<TextBox Name="tbText3" TextWrapping="Wrap" Text="" MinWidth="80" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Grid.Row="1" Grid.Column="1">
<StackPanel>
<ContentPresenter ContentSource="SecondContent"/>
</StackPanel>
</Border>
</Grid>
</ControlTemplate>
</UserControl.Template>
</UserControl>
<my:BaseClass>
<my:BaseClass.FirstContent>
<StackPanel>
<Label Content="Test:"/>
<ComboBox ItemsSource="{Binding TestTyps}" MinWidth="80"/>
</StackPanel>
<my:BaseClass.FirstContent>
<my:BaseClass.SecondContent>
<StackPanel>
<Label Content="Test10:"/>
<TextBox Text="{Binding Whatever}" MinWidth="80"/>
</StackPanel>
<my:BaseClass.SecondContent>
</my:BaseClass>
I gave the point to Firo, because he gave me the right answer. But I want to give some final thoughts, so everyone can benefit from it.
For the xaml "base-class":
<UserControl
x:Class="BaseImport.BaseClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Grid>
<Border Grid.Row="0" Grid.Column="0">
<StackPanel>
<Label Content="Text1:"/>
<ComboBox Name="cbText1" MinWidth="80"/>
</StackPanel>
</Border>
<Border Grid.Row="0" Grid.Column="1">
<StackPanel>
<Label Content="DB:"/>
<ComboBox
Name="cbxDB"
ItemsSource="{Binding DBs}"
SelectedItem="{Binding DB}"
MinWidth="80"
SelectionChanged="selectionChanged"
Loaded="DB_Loaded">
<!--
here the DataContext can be set differently
<ComboBox.DataContext>
<Views:DBViewModel/>
</ComboBox.DataContext>
-->
</ComboBox>
</StackPanel>
</Border>
<!-- the content placeholder -->
<Border Grid.Row="0" Grid.Column="2">
<StackPanel MinWidth="80">
<ContentControl
Content="{Binding ContentOne}"
ContentTemplate="{Binding ContentOneTemplate}"
ContentTemplateSelector="{Binding ContentOneTemplateSelector}"/>
</StackPanel>
</Border>
<Border Grid.Row="0" Grid.Column="3">
<StackPanel MinWidth="80">
<ContentControl
Content="{Binding ContentTwo}"
ContentTemplate="{Binding ContentTwoTemplate}"
ContentTemplateSelector="{Binding ContentTwoTemplateSelector}"/>
</StackPanel>
</Border>
</Grid>
</ControlTemplate>
</UserControl.Template>
</UserControl>
For the "base-class":
public partial class BaseClass : UserControl
{
public BaseClass(BaseViewModel _bvm)
{
InitializeComponent();
// set DataContext for all other controls
DataContext = _bvm;
}
#region DependencyProperty
public static readonly DependencyProperty ContentOneProperty = DependencyProperty.Register("ContentOne", typeof(object), typeof(BaseImportClass));
public static readonly DependencyProperty ContentOneTemplateProperty = DependencyProperty.Register("ContentOneTemplate", typeof(DataTemplate), typeof(BaseImportClass));
public static readonly DependencyProperty ContentOneTemplateSelectorProperty = DependencyProperty.Register("ContentOneTemplateSelector", typeof(DataTemplateSelector), typeof(BaseImportClass));
public static readonly DependencyProperty ContentTwoProperty = DependencyProperty.Register("ContentTwo", typeof(object), typeof(BaseImportClass));
public static readonly DependencyProperty ContentTwoTemplateProperty = DependencyProperty.Register("ContentTwoTemplate", typeof(DataTemplate), typeof(BaseImportClass));
public static readonly DependencyProperty ContentTwoTemplateSelectorProperty = DependencyProperty.Register("ContentTwoTemplateSelector", typeof(DataTemplateSelector), typeof(BaseImportClass));
public object ContentOne
{
get { return GetValue(ContentOneProperty); }
set { SetValue(ContentOneProperty, value); }
}
public DataTemplate ContentOneTemplate
{
get { return (DataTemplate)GetValue(ContentOneTemplateProperty); }
set { SetValue(ContentOneTemplateProperty, value); }
}
public DataTemplateSelector ContentOneTemplateSelector
{
get { return (DataTemplateSelector)GetValue(ContentOneTemplateSelectorProperty); }
set { SetValue(ContentOneTemplateSelectorProperty, value); }
}
public object ContentTwo
{
get { return GetValue(ContentTwoProperty); }
set { SetValue(ContentTwoProperty, value); }
}
public DataTemplate ContentTwoTemplate
{
get { return (DataTemplate)GetValue(ContentTwoTemplateProperty); }
set { SetValue(ContentTwoTemplateProperty, value); }
}
public DataTemplateSelector ContentTwoTemplateSelector
{
get { return (DataTemplateSelector)GetValue(ContentTwoTemplateSelectorProperty); }
set { SetValue(ContentTwoTemplateSelectorProperty, value); }
}
#endregion
}
For the "derived" class xaml:
<UserControl x:Class="WpfApp1.DerivedClass"
xmlns:base="clr-namespace:BaseImport.Views;assembly=BaseImport"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<StackPanel>
<base:BaseClass Name="bc">
<base:BaseClass.ContentOneTemplate>
<DataTemplate>
<StackPanel>
<Label Content="Test:"/>
<ComboBox
ItemsSource="{Binding TestTyps}"
SelectedItem="{Binding TestTyp}"
SelectionChanged="TestTypChanged"
Loaded="TestTypLoaded">
<!--
here the DataContext can be set differently
<ComboBox.DataContext>
<Views:ViewModelXYZ/>
</ComboBox.DataContext>
-->
</ComboBox>
</StackPanel>
</DataTemplate>
</base:BaseClass.ContentOneTemplate>
</base:BaseClass>
</StackPanel>
</UserControl>
For the "derived" class:
public partial class DerivedClass : UserControl
{
ViewModelABC vmabc = null;
public DerivedClass(ViewModel _vm) : this()
{
vmabc = _vm;
this.DataContext = vmabc;
bc.DataContext = vmabc; // or another viewmodel that holds TestTyps and TestTyp or leave it for ViewModelXYZ
}
private void TestTypChanged(object sender, SelectionChangedEventArgs e)
{
PropertyChanged();
}
private void TestTypLoaded(object sender, RoutedEventArgs e)
{
(sender as ComboBox).SelectedValue = (this.DataContext as ViewModel(XYZ/ABC).TestTyp;
}
}
That is what I came up.
I hope that helps others.

Databinding to command inside of listview not working in UWP/MVVM-Light

I want to have a Delete button for every element in my ListView, I searched stackoverflow but none answer my question.
I tried giving my ListView a x:Name="QuizListView" and using ElementName inside the ListView to bind the command to the button.
QuizOverview.xaml
<Page
x:Name="QuizOverviewPage"
x:Class="UwpApp.View.QuizOverview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UwpApp.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding QuizOverviewInstance, Source={StaticResource Locator}}">
<StackPanel Margin="20">
<TextBlock Text="Quizzen" FontSize="48"/>
<ListView x:Name="QuizListView" ItemsSource="{Binding Quizzes}" Margin="0,20" SelectionMode="Single" SelectionChanged="QuizListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<ListViewItem>
<StackPanel Orientation="Horizontal">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="2" Height="100" Width="400" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="36"></TextBlock>
</Border>
<Button VerticalAlignment="Center" Padding="20" Margin="20">Edit</Button>
<Button VerticalAlignment="Center" Padding="20" Margin="0" Command="{Binding Path=DataContext.DeleteQuizCommand, ElementName=QuizListView}" CommandParameter="{Binding}">Delete</Button>
</StackPanel>
</ListViewItem>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Padding="20" Command="{Binding CreateQuizCommand}">Add New Quiz</Button>
</StackPanel>
</Page>
QuizOverviewViewModel.cs
public class QuizOverviewViewModel : ViewModelBase
{
public string Title { get; set; }
public ObservableCollection<Quiz> Quizzes { get; set; }
public RelayCommand<Quiz> DeleteQuizCommand { get; set; }
public RelayCommand CreateQuizCommand { get; set; }
public QuizOverviewViewModel()
{
Title = "Quizzen";
Quizzes = new ObservableCollection<Quiz> { new Quiz(1, "Test Quiz 1"), new Quiz(2, "Test Quiz 2"), new Quiz(3, "Test Quiz 3") };
DeleteQuizCommand = new RelayCommand<Quiz>(DeleteQuiz);
CreateQuizCommand = new RelayCommand(CreateQuizTest);
}
public void DeleteQuiz(Quiz quiz)
{
Quizzes.Remove(Quizzes.Single(i => i.Id == quiz.Id));
}
public void CreateQuizTest()
{
Quizzes.Add(new Quiz(4, "Test Quiz Creation!"));
}
}
Quiz.cs
namespace UwpApp.Model
{
public class Quiz
{
public long Id { get; set; }
public string Name { get; set; }
public Quiz(long id, string name)
{
Id = id;
Name = name;
}
}
}
The Button does nothing with my current code, while the command does work outside of the ListView.
Databinding to command inside of listview not working in UWP/MVVM-Light
The problem is that you insert ListViewItem in to DataTemplate. It will cause that ListViewItem contains sub-ListViewItem in the Visual Tree and you could not access correct DataContext with element name in your button. Please remove ListViewItem from your code.
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="2" Height="100" Width="400" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="36"></TextBlock>
</Border>
<Button VerticalAlignment="Center" Padding="20" Margin="20">Edit</Button>
<Button VerticalAlignment="Center" Padding="20" Margin="0" Command="{Binding Path=DataContext.DeleteQuizCommand, ElementName=QuizListView}" CommandParameter="{Binding}">Delete</Button>
</StackPanel>
</DataTemplate>

Closing an Open Window Using MVVM Pattern, Produces System.NullReferenceException error

I'm trying to learn MVVM pattern using WPF C#. And I'm running into an error when trying to close an opened window after saving information to an sqlite database. When the command to save a new contact is raised, I am getting an error on HasAddedContact(this, new EventArgs());
Error: System.NullReferenceException: 'Object reference not set to an instance of an object.'
My ViewModel:
public class NewContactViewModel : BaseViewModel
{
private ContactViewModel _contact;
public ContactViewModel Contact
{
get { return _contact; }
set { SetValue(ref _contact, value); }
}
public SaveNewContactCommand SaveNewContactCommand { get; set; }
public event EventHandler HasAddedContact;
public NewContactViewModel()
{
SaveNewContactCommand = new SaveNewContactCommand(this);
_contact = new ContactViewModel();
}
public void SaveNewContact()
{
var newContact = new Contact()
{
Name = Contact.Name,
Email = Contact.Email,
Phone = Contact.Phone
};
DatabaseConnection.Insert(newContact);
HasAddedContact(this, new EventArgs());
}
}
SaveNewContactCommand:
public class SaveNewContactCommand : ICommand
{
public NewContactViewModel VM { get; set; }
public SaveNewContactCommand(NewContactViewModel vm)
{
VM = vm;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
VM.SaveNewContact();
}
}
NewContactWindow.Xaml.Cs code behind:
public partial class NewContactWindow : Window
{
NewContactViewModel _viewModel;
public NewContactWindow()
{
InitializeComponent();
_viewModel = new NewContactViewModel();
DataContext = _viewModel;
_viewModel.HasAddedContact += Vm_ContactAdded;
}
private void Vm_ContactAdded(object sender, EventArgs e)
{
this.Close();
}
}
Adding additional code where I call the new window:
public class ContactsViewModel
{
public ObservableCollection<IContact> Contacts { get; set; } = new ObservableCollection<IContact>();
public NewContactCommand NewContactCommand { get; set; }
public ContactsViewModel()
{
NewContactCommand = new NewContactCommand(this);
GetContacts();
}
public void GetContacts()
{
using(var conn = new SQLite.SQLiteConnection(DatabaseConnection.dbFile))
{
conn.CreateTable<Contact>();
var contacts = conn.Table<Contact>().ToList();
Contacts.Clear();
foreach (var contact in contacts)
{
Contacts.Add(contact);
}
}
}
public void CreateNewContact()
{
var newContactWindow = new NewContactWindow();
newContactWindow.ShowDialog();
GetContacts();
}
}
ContactsWindow.Xaml
<Window x:Class="Contacts_App.View.ContactsWindow"
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"
xmlns:local="clr-namespace:Contacts_App.View"
xmlns:vm="clr-namespace:Contacts_App.ViewModel"
mc:Ignorable="d"
Title="Contacts Window" Height="320" Width="400">
<Window.Resources>
<vm:ContactsViewModel x:Key="vm"/>
</Window.Resources>
<StackPanel Margin="10">
<Button
Content="New Contact"
Command="{Binding NewContactCommand}"/>
<TextBox Margin="0,5,0,5"/>
<ListView
Height="200"
Margin="0,5,0,0"
ItemsSource="{Binding Contacts}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Window>
NewContactWindow.Xaml
<Window x:Class="Contacts_App.View.NewContactWindow"
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"
xmlns:local="clr-namespace:Contacts_App.View"
xmlns:vm="clr-namespace:Contacts_App.ViewModel"
mc:Ignorable="d"
Title="New Contact Window" Height="250" Width="350">
<Window.Resources>
<vm:NewContactViewModel x:Key="vm"/>
</Window.Resources>
<Grid>
<StackPanel
Margin="10">
<Label Content="Name" />
<TextBox
Text="{Binding Source={StaticResource vm}, Path=Contact.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Email" />
<TextBox
Text="{Binding Source={StaticResource vm}, Path=Contact.Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Phone Number" />
<TextBox
Text="{Binding Source={StaticResource vm}, Path=Contact.Phone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Button
Content="Save"
Command="{Binding Source={StaticResource vm}, Path=SaveNewContactCommand}"/>
</StackPanel>
</Grid>
</Window>
You're creating NewContactWindow's viewmodel in the constructor, correctly assigning it to DataContext, and correctly adding a handler to that event. Unfortunately, you also create a second instance of the same viewmodel in resources, and you manually set the Source property of all the bindings to use the one in the resources, which doesn't have the event handler.
Window.DataContext, which you set in the constructor, is the default Source for any binding in the Window XAML. Just let it do its thing. I also removed all the redundant Mode=TwoWay things from the Bindings to TextBox.Text, since that property is defined so that all bindings on it will be TwoWay by default. I don't think UpdateSourceTrigger=PropertyChanged is doing anything necessary or helpful either: That causes the Binding to update your viewmodel property every time a key is pressed, instead of just when the TextBox loses focus. But I don't think you're doing anything with the properties where that would matter; there's no validation or anything. But TextBox.Text is one of the very few places where that's actually used, so I left it in.
You should remove the analagous viewmodel resource in your other window. It's not doing any harm, but it's useless at best. At worst, it's an attractive nuisance. Kill it with fire and bury the ashes under a lonely crossroads at midnight.
<Window x:Class="Contacts_App.View.NewContactWindow"
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"
xmlns:local="clr-namespace:Contacts_App.View"
xmlns:vm="clr-namespace:Contacts_App.ViewModel"
mc:Ignorable="d"
Title="New Contact Window" Height="250" Width="350">
<Grid>
<StackPanel
Margin="10">
<Label Content="Name" />
<TextBox
Text="{Binding Contact.Name, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Email" />
<TextBox
Text="{Binding Contact.Email, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Phone Number" />
<TextBox
Text="{Binding Contact.Phone, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Button
Content="Save"
Command="{Binding SaveNewContactCommand}"/>
</StackPanel>
</Grid>
</Window>

WPF Dynamic add ListViewItem with detals

I want to add ListViewItem with changed details like image's link, text in textbox etc. How can I do it?
<ListView VerticalAlignment="Bottom" Margin="10" Height="170" Foreground="LightSteelBlue">
<ListViewItem>
<StackPanel Orientation="Horizontal">
<TextBlock Text="01" VerticalAlignment="Center"/>
<Ellipse Margin="20,0" Width="30" Height="30" VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush ImageSource="images/pobrane.jpg"/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Text="Three Days Grace - I Hate Everything About You (Official Music Video)" Width="115" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
<TextBlock Text="3:45" Margin="10,0" VerticalAlignment="Center" />
</StackPanel>
</ListViewItem>
</ListView>
I want to make function which will add the same code like i showed you with changed details.
You can use the ItemTemplate and the ItemsSource properties of the WPF Listview and the Binding concepts.
Just for an example, starting from your question:
You can add the following code to the MainWindow files of a new WPF project:
The MainWindow.xaml file should look like this:
<Window x:Class="WpfApp1.MainWindow"
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"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Click="Button_Click"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="10"
Content="Add item"/>
<ListView VerticalAlignment="Bottom"
Margin="10"
Height="170"
ItemsSource="{Binding Tracks}"
Foreground="LightSteelBlue">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"
VerticalAlignment="Center" />
<Ellipse Margin="20,0"
Width="30"
Height="30"
VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush ImageSource="{Binding Image}" />
</Ellipse.Fill>
</Ellipse>
<TextBlock Text="{Binding Name}"
Width="115"
TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
<TextBlock Text="{Binding Length}"
Margin="10,0"
VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
And the MainWindow.xaml.cs file should look like this:
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Track> Tracks { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Tracks = new ObservableCollection<Track>();
AddTrack("01","Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg")));
}
public void AddTrack (string number, string name, string length, ImageSource image)
{
var track = new Track();
track.Number = number;
track.Name = name;
track.Length = length;
track.Image = image;
Tracks.Add(track);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AddTrack("01", "Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg")));
}
}
public class Track
{
public string Number { get; set; }
public string Name { get; set; }
public string Length { get; set; }
public ImageSource Image { get; set; }
}
}
Of course, this is just as a starting point. You should go on searching and reading the MVVM concepts and move the logic to a viewmodel.

Attaching an Event to an item in a listviewItem/Deleting ListviewItem when clicked on child element

I have a Listview which contains which is a drag and drop listview, each listview items contains and icon (which is an MahApps X icon) and a file name. I want that every ListviewItem has this x icon, and when user click on the icon it will remove the file name from the Listview or the ObservableCollection fileNames. Unfortunately it seems in this case I don't know how to handle this event, what ever code i wrote was wrong. My question is to show me how to do this or explain me how will the event handling work in this case and how to get the ListViewItem from the sender. Thank you
This is the XAML:
<ListView x:Name="DropList" DockPanel.Dock="Left" Foreground="White"
Drop="DropList_Drop"
DragEnter="DropList_DragEnter"
AllowDrop="True"
DragOver="DropList_DragOver" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle x:Name="DeleteAttachment" Height="Auto" Width="Height" MouseLeftButtonDown="DeleteAttachment_MouseLeftButtonDown">
<Rectangle.Fill>
<VisualBrush Visual="{StaticResource appbar_checkmark_cross}" />
</Rectangle.Fill>
</Rectangle>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This is the code:
ObservableCollection<String> fileNames;
public Page()
{
InitializeComponent();
DropList.ItemsSource = fileNames;
}
private void DeleteAttachment_MouseLeftButtonDown(object sender, MouseButtonEventArgs) {
fileNames.Remove();
}
Try this:
XAML:
<Controls:MetroWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:local="clr-namespace:MahApps.Metro.Application24"
x:Class="MahApps.Metro.Application24.MainWindow"
BorderBrush="{StaticResource AccentColorBrush}"
BorderThickness="2"
Title="MainWindow"
Height="300"
Width="300">
<Grid>
<ListView x:Name="list1" ItemsSource="{Binding Data}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Height="15" Width="15" VerticalAlignment="Center" MouseLeftButtonDown="r1_MouseLeftButtonDown">
<Rectangle.Fill>
<VisualBrush Visual="{StaticResource appbar_checkmark_cross}" />
</Rectangle.Fill>
</Rectangle>
<TextBlock Text="{Binding}" Padding="5,5,5,5" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
MainWindow:
public partial class MainWindow : MetroWindow
{
MyViewModel vm;
public MainWindow()
{
InitializeComponent();
vm = new MyViewModel();
DataContext = vm;
}
private void r1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Rectangle r = sender as Rectangle;
vm.Data.Remove(r.DataContext.ToString());
}
}
ViewModel:
public class MyViewModel
{
public ObservableCollection<string> Data { get; set; }
public MyViewModel()
{
Data = new ObservableCollection<string>
{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5"
};
}
}

Categories