Im trying to implement a simple create-function in my win 8 app. Im trying to use the MVVM-pattern. Im trying to pass a class into my view with my view.model and then simply have a couple of textboxes that lets me create a new object. Here is the ViewModel and class:
public class CreateViewModel : ViewModelBase
{
public Place Place { get; set; }
}
public class Place
{
[PrimaryKey, AutoIncrement]
public int PlaceId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
In an MVC-application i would have done some #Html.TextBoxFor and created a post-method.
In XAML I am not sure of how to do this.
The viewmodel gets passed in to view as it should. I can acess its properties like this:
<TextBox Grid.Row="0" Text="{Binding Path=Place.Title}"/>
<TextBox Grid.Row="0" Text="{Binding Path=Place.Description}"/>
But i do not understand how I can "post" new values back to the ViewModel and create a new object?
EDIT:
From what I can see this is a way to have commands in my ViewModel:
public class CreateViewModel : ViewModelBase
{
public RelayCommand CreatePlaceCommand
{
get;
private set;
}
public Place Place { get; set; }
public CreateViewModel()
{
InitializeCommands();
}
private void InitializeCommands()
{
CreatePlaceCommand =
new RelayCommand(() =>
{
//What goes here?
});
}
}
I also added this code to my XAML:
<TextBox Grid.Row="0" Text="{Binding Place.Title,Mode=TwoWay}"/>
<TextBox Grid.Row="0" Text="{Binding Place.Description,Mode=TwoWay}"/>
<Button Grid.Row="0" Content="Click"
Command="{Binding CreatePlaceCommand}" >
</Button>
Am I on the right track here? Its pretty confusing =)
Here, study this simple example to get hold of MVVM/DataBinding/Commands. It's really simplistic but it should show the "patterns" to use. There's plenty of libs (like MVVMLight) to make commanding etc. simpler and more powerful.
So assuming we have Place entity
public class Place
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public override string ToString()
{
return string.Format("Id={0},Title={1},Description={2}",
Id, Title, Description);
}
}
And you have MainWindow.xaml in your application named wpfApplication1
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
Title="MainWindow"
Height="116"
Width="250">
<!-- set datacontext to mainviewmodel -->
<Window.DataContext>
<wpfApplication1:MainViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<!-- input textboxes for title and description -->
<StackPanel Grid.Row="0">
<TextBox Text="{Binding Place.Title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="25" />
<TextBox Text="{Binding Place.Description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="25" />
</StackPanel>
<!-- button bound to save command, declared in viewmodel -->
<Button Grid.Row="1" Content="Save" Command="{Binding SaveCommand}" />
</Grid>
</Window>
Related MainWindows.xaml.cs contains nothing but InitializeComponents().
Now your MainViewModel, "taking care of all things", could look like
public class MainViewModel
{
private Place _place;
public MainViewModel()
{
// create and register new save command
SaveCommand = new SaveCommand(this);
CommandManager.RegisterClassCommandBinding(
typeof(MainViewModel), new CommandBinding(SaveCommand));
}
// property to hold place data, exposed in UI
public Place Place
{
get { return _place ?? (_place = new Place()); }
set { _place = value; }
}
public ICommand SaveCommand { get; private set; }
}
And simplistic save command implementation used in viewmodel
public class SaveCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private readonly MainViewModel _context;
public SaveCommand(MainViewModel context)
{
_context = context;
}
public void Execute(object parameter)
{
Console.WriteLine(string.Format("Do something with {0}", _context.Place));
}
public bool CanExecute(object parameter)
{
return true;
}
}
Now, this would give you UI, something like below (this example is not type of Store app)
And clicking a button would then spit out
Do something with Id=0,Title=Title,Description=and teh description
Related
I'm developing a WPF application using caliburn.micro MVVM framework..
In-order to develop a search screen, I need to dynamically load fields into the view, based on model properties.
Consider below view and view model:
SearchViewModel
SearchView
Let's assume T is a type of Product in below example.
public class SearchViewModel<T>
{
public T Item{get;set;}
}
public class Product
{
public int Id{get;set;}
public string Name{get;set;}
public string Description{get;set;}
}
I have a user control called SearchView.xaml with no contents on it.
Whenever View is loaded new fields should be added to the view and field should be bound to the properties.
According to above code example, there are 3 public properties in the Product class, therefore 3 TextBoxes should be added to the view dynamically. When user enters data in the text field, corresponding property should be updated.
Is this possible?
Can any experts help me to achieve this by providing some examples?
I would propose going about this differently. Instead of thinking about dynamically adding properties to a view / model, I would think about adding information about those properties to a list on the viewmodel. That list would then be bound to an ItemsControl with a template that looks like a TextBox.
So your view-model would have a property on it for the "thing" you want to examine. In the setter for this property, use reflection to enumerate the properties you are interested in, and add an instance of some kind of FieldInfo class (that you create) to the list of properties with the binding.
This has the benefit of keeping everything all MVVM compatible too, and there is no need to dynamically create controls with your own code.
The example below uses my own MVVM library (as a nuget package) rather than caliburn.micro, but it should be similar enough to follow the basic idea. The full source code of the example can be downloaded from this BitBucket repo.
As you can see in the included screenshots, the search fields are created dynamically on the view without any code in the view. Everything is done on the viewmodel. This also gives you easy access to the data that the user enters.
The view-model:
namespace DynamicViewExample
{
class MainWindowVm : ViewModel
{
public MainWindowVm()
{
Fields = new ObservableCollection<SearchFieldInfo>();
SearchableTypes = new ObservableCollection<Type>()
{
typeof(Models.User),
typeof(Models.Widget)
};
SearchType = SearchableTypes.First();
}
public ObservableCollection<Type> SearchableTypes { get; }
public ObservableCollection<SearchFieldInfo> Fields { get; }
private Type _searchType;
public Type SearchType
{
get { return _searchType; }
set
{
_searchType = value;
Fields.Clear();
foreach (PropertyInfo prop in _searchType.GetProperties())
{
var searchField = new SearchFieldInfo(prop.Name);
Fields.Add(searchField);
}
}
}
private ICommand _searchCommand;
public ICommand SearchCommand
{
get { return _searchCommand ?? (_searchCommand = new SimpleCommand((obj) =>
{
WindowManager.ShowMessage(String.Join(", ", Fields.Select(f => $"{f.Name}: {f.Value}")));
})); }
}
}
}
The SearchFieldInfo class:
namespace DynamicViewExample
{
public class SearchFieldInfo
{
public SearchFieldInfo(string name)
{
Name = name;
}
public string Name { get; }
public string Value { get; set; } = "";
}
}
The view:
<Window
x:Class="DynamicViewExample.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:local="clr-namespace:DynamicViewExample"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
d:DataContext="{d:DesignInstance local:MainWindowVm}"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ComboBox
Grid.Row="0"
ItemsSource="{Binding Path=SearchableTypes}"
SelectedItem="{Binding Path=SearchType}" />
<ItemsControl Grid.Row="1" ItemsSource="{Binding Path=Fields}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBox Width="300" Text="{Binding Path=Value}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Grid.Row="2" Command="{Binding Path=SearchCommand}">Search</Button>
</Grid>
</Window>
The model classes:
class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Id { get; set; }
}
class Widget
{
public string ModelNumber { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Here is a basic example of how you could generate a TextBox per public property of the T in the control using reflection.
SearchView.xaml:
<Window x:Class="WpfApplication4.SearchView"
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:WpfApplication4"
mc:Ignorable="d"
Title="SearchView" Height="300" Width="300">
<StackPanel x:Name="rootPanel">
</StackPanel>
</Window>
SearchView.xaml.cs:
public partial class SearchView : UserControl
{
public SearchView()
{
InitializeComponent();
DataContextChanged += SearchView_DataContextChanged;
DataContext = new SearchViewModel<Product>();
}
private void SearchView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null)
{
Type genericType = e.NewValue.GetType();
//check the DataContext was set to a SearchViewModel<T>
if (genericType.GetGenericTypeDefinition() == typeof(SearchViewModel<>))
{
//...and create a TextBox for each property of the type T
Type type = genericType.GetGenericArguments()[0];
var properties = type.GetProperties();
foreach(var property in properties)
{
TextBox textBox = new TextBox();
Binding binding = new Binding(property.Name);
if (!property.CanWrite)
binding.Mode = BindingMode.OneWay;
textBox.SetBinding(TextBox.TextProperty, binding);
rootPanel.Children.Add(textBox);
}
}
}
}
}
The other option will obviously be to create a "static" view for each type of T and define the TextBox elements in the XAML markup as usual.
I'm trying to build a DTO to store the software configuration, but I'm stuck because my view is not sending the data to my ViewModel and also to my DTO.
I need to transfer 2 textbox and 3 combobox to my DTO, but using this code the values are always empty.
My ViewModel:
public class ViewModelProcessamentoArquivo : ViewModelBase
{
private PesquisaConfiguracao pesquisaConfiguracao;
public PesquisaConfiguracao PesquisaConfiguracao
{
get { return pesquisaConfiguracao; }
set
{
pesquisaConfiguracao = value;
base.OnPropertyChanged("PesquisaConfiguracao");
}
}
}
My DTO/Model
public class PesquisaConfiguracao
{
public string ArquivoOrigem { get; set; }
public string ArquivoDestino { get; set; }
public string TipoPesquisa { get; set; }
public string PesquisaVeicular { get; set; }
public string PesquisaCrediticia { get; set; }
}
And my View is like this.
<TextBox Name="txtBuscarArquivoOrigem" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Height="30" Margin="10, 0" Text="{Binding PesquisaConfiguracao.ArquivoOrigem}" />
<TextBox x:Name="txtBuscarArquivoDestino" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="3" Height="30" Margin="10, 0" Text="{Binding PesquisaConfiguracao.ArquivoDestino}" IsEnabled="false" />
...
Do you guys know why it's happening? I've used something similar in my other project and worked just fine. Also if you have any other possibly way to fix this issue, please comment!
First UpdateSourceTrigger PropertyChanged, that way the target (view) will update your source object on every change:
<TextBox Name="txtBuscarArquivoOrigem" Height="30" Text="{Binding PesquisaConfiguracao.ArquivoOrigem, UpdateSourceTrigger=PropertyChanged}" />
Then implement in your source object the INotifyPropertyChange Interface on it's properties in order to update the view when the value has changed:
private string _arquivoOrigem;
public string ArquivoOrigem
{
get
{
return _arquivoOrigem;
}
set
{
_arquivoOrigem = value;
OnPropertyChanged("ArquivoOrigem");
}
}
Put a BreakPoint in the property setter and it will break there when you change the value in the view TextBox.
If it doesn't work for you probably forgot to set your DataContext to your ViewModel:
<Window x:Class="WpfApplication1.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"
DataContext="{StaticResource MainViewModel}">
Or did not initialize your source object:
public MainViewModel()
{
pesquisaConfiguracao = new PesquisaConfiguracao
{
ArquivoDestino = "aaa",
ArquivoOrigem = "bbb",
PesquisaCrediticia = "ccc",
PesquisaVeicular = "dddd",
TipoPesquisa = "eee"
};
}
I'm trying to execute methods based on listview items data. In addition to that, the button, which triggers the command, should only be enabled, if "CanExecute" method of the listview item returns true.
Both methods, "MyCommand" and "CanExecute", are included in my ViewModel.
Unfortunately I'm not sure how to pass the items information correctly to both methods in order to be conform with the PRISM 6 framework.
So my first approach was to do it like the following :
Model
public class MyModel
{
public string Name { get; set; }
public string Version { get; set; }
public int Identifier { get; set; }
}
ViewModel
public class MyViewModel : BindableBase
{
private ObservableCollection<MyModel> _models = new ObservableCollection<MyModel>();
public ObservableCollection<MyModel> Models
{
get { return _models; }
set { SetProperty(ref _models, value); }
}
public DelegateCommand VerifyCommand { get; set; }
public MyViewModel()
{
//Add test data
for (int i = 0; i < 5; i++)
{
MyModel model = new MyModel();
model.Name = "Random Text";
model.Version = "Random Text";
model.Identifier = i;
Models.Add(model);
}
//Doesn't work, because I don't reference to "Models"
//How to do that?
VerifyCommand = new DelegateCommand(DoCommand, CanExecute).ObservesProperty<string>(() => Name).ObservesProperty<string>(() => Version);
}
private bool CanExecute()
{
//Obviously this doesn't work, because "Version" and "Name"
//don't belong to the selected "Models" item of the listview
//What is the "bridge", to know which item of Models was clicked (button)
return !String.IsNullOrWhiteSpace(Version) && !String.IsNullOrWhiteSpace(Name);
}
private void DoCommand()
{
//Do something special
}
}
View
<ListView ItemsSource="{Binding Models}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="Auto" Margin="0,0,0,10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Tag="VERSION" Text="{Binding Version, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Row="1" Tag="NAME" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding ElementName=root, Path=DataContext.VerifyCommand}" Content="Verify" Grid.Row="2">
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The link between View and ViewModel is done by using:
prism:ViewModelLocator.AutoWireViewModel="True"
in my View (this works).
So in summary:
How does it work, PRISM conform, to 1. Enable the items button only if CanExecute is true and 2. to execute "DoCommand" method and passing items information to that (root element of the button -> In this case the ListViewItem (MyModel).
Any help would be greatly appreciated.
Short answer: put the command in the item's viewmodel.
Long answer:
Here's an example of what I mean in the comment above. I've omitted the observability of the collections, if you really need an observable collection of models and an observable collection of view models, prepare yourself for a lot of boring two-way-sync-code...
Model:
internal class ItemModel
{
public string Name { get; set; }
public string Version { get; set; }
public int Identifier { get; set; }
}
ViewModels (one for the collection of items, that is, your MyViewModel, and one for the item):
internal class MyCollectionViewModel : BindableBase
{
private readonly List<ItemModel> _models = new List<ItemModel>();
public MyCollectionViewModel()
{
//Add test data
for (var i = 0; i < 5; i++)
_models.Add( new ItemModel
{
// to prove that CanExecute is actually evaluated...
Name = i == 3 ? "Random Text" : string.Empty,
Version = "Random Text",
Identifier = i
} );
}
public IReadOnlyCollection<ItemViewModel> TheCollection => _models.Select( x => new ItemViewModel( x ) ).ToList();
}
internal class ItemViewModel : BindableBase
{
public ItemViewModel( ItemModel item )
{
_item = item;
VerifyCommand = new DelegateCommand( () =>
{
/* Do something */
}, () => !string.IsNullOrWhiteSpace( Version ) && !string.IsNullOrWhiteSpace( Name ) );
}
public string Name => _item.Name;
public string Version => _item.Version;
public int Identifier => _item.Identifier;
public DelegateCommand VerifyCommand
{
get;
}
private readonly ItemModel _item;
}
View:
<ListView ItemsSource="{Binding TheCollection}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="Auto" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding Version, Mode=OneWay}" />
<TextBox Grid.Column="1" Text="{Binding Name, Mode=OneWay}" />
<Button Grid.Column="2" Command="{Binding VerifyCommand}" Content="Verify"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
How do I get my custom item collection to show up in my list view using WPF data bindings?
I have a tried to make a ViewModel and a custom collection that the ViewModel manipulates, in an attempt to get this collection to show up in a listview. I have a view model and a custom collection and a custom item class:
public class TranslationViewModel
{
public TranslationViewModel() { this.translatedItems = new TransListboxCollection(); }
public TransListboxCollection translatedItems { get; private set; }
public void addTranslatedItem(TransListboxItem message)
{
translatedItems.Add(message);
}
}
public class TransListboxCollection : BindingList<TransListboxItem>
{
public TransListboxCollection()
{
//initialize
}
}
public class TransListboxItem : INotifyPropertyChanged
{
private String _rawString;
private String _tString;
public String rawString
{
get { return _rawString; }
set { _rawString = value; NotifyPropertyChanged("rawString"); }
}
public String tString
{
get { return _tString; }
set { _tString = value; NotifyPropertyChanged("tString"); }
}
public TransListboxItem(String value)
{
this.tString = value;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public override string ToString()
{
return this.tString;
}
}
I have a WPF element hosted in a windows form
public partial class wGlobal : UserControl
{
public TranslationViewModel tvm { get; set; }
public wGlobal()
{
InitializeComponent();
this.DataContext = tvm;
}
}
The XAML code for such
<UserControl
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"
xmlns:local="clr-namespace:MHF_Transcoder_3" x:Class="MHF_Transcoder_3.wGlobal"
mc:Ignorable="d"
d:DesignWidth="1000" d:DesignHeight="150">
<Grid Width="1000" Height="150">
<ListView x:Name="listView1" ItemsSource="{Binding tvm}" HorizontalAlignment="Left" Width="1000" Height="150" VerticalAlignment="Top" Background="Black" Foreground="White" RenderTransformOrigin="0.5,0.5">
<DataTemplate>
<TextBlock Text="{Binding tString}" ToolTipService.ToolTip="{Binding rawString}" />
</DataTemplate>
</ListView>
</Grid>
and I have that element hosted in a windows form control
public partial class frmGlobal : Form
{
wGlobal xamlForm;
TranslationViewModel tvm;
public frmGlobal()
{
InitializeComponent();
tvm = new TranslationViewModel();
xamlForm = (wGlobal)elementHost1.Child;
xamlForm.tvm = tvm;
}
delegate void addMessageCallback(TransListboxItem message);
public void addMessage(TransListboxItem message) {
tvm.addTranslatedItem(message);
}
}
When I get the program up and launch everything, all my list view says is "System.Windows.DataTemplate". I've never really worked with WPF or data bindings before. I'm open to any and all advice and suggestions. Please help me get this setup and properly working.
Wrap Datatemplate with ItemTemplate
<ListView x:Name="listView1" ItemsSource="{Binding translatedItems}" HorizontalAlignment="Left" Width="1000" Height="150" VerticalAlignment="Top" Background="Black" Foreground="White" RenderTransformOrigin="0.5,0.5">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding tString}" ToolTipService.ToolTip="{Binding rawString}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Also as the tvm is the datacontext, you must bind to the collection "translatedItems"
So I'm brand new to WPF data binding, and it is.. complicated. At this point, I'm trying to just create a list of premade test items and have it displayed in a listbox with a data template when I press a button. After hours of puzzling through tutorials and MSDN this is the best I could come up with.
The data item I want to make a list from:
class ListingItem
{
private string title;
private string user;
private string category;
//Dummy constructor for test purposes
public ListingItem()
{
title = "TestTitle";
user = "TestUser";
category = "TestCatagory";
}
}
The quick and dirty list creator:
class ListMaker
{
public static List<ListingItem> getListing()
{
List<ListingItem> listing = new List<ListingItem>();
for(int i = 0; i <100; i++)
{
listing.Add(new ListingItem());
}
return listing;
}
}
The XAML of the list itself:
<ListBox x:Name="Listing">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="Gray" Margin="25,0,0,0" Text="{Binding user}"/>
<TextBlock Foreground="Gray" Margin="25,0,0,0" Text="{Binding category}"/>
</StackPanel>
<TextBlock Foreground="Black" Width="270" TextWrapping="Wrap" Text="{Binding title}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
And finally, the button click event which is SUPPOSED to make the magic happen:
private void TabClickEvent(object sender, RoutedEventArgs e)
{
Listing.DataContext = RedditScanner.getListing();
}
Problem is, obviously, the magic is not happening. No errors or anything so easy, I just press that button and dont see any change to the list box. Any help with this?
You cannot bind to private fields. Not even to public fields I think.
Use properties:
class ListingItem
{
//private string title;
//private string user;
//private string category;
public string Title { get; set; }
public string User { get; set; }
public string Category { get; set; }
//Dummy constructor for test purposes
public ListingItem()
{
Title = "TestTitle";
User = "TestUser";
Category = "TestCatagory";
}
}
And for full databinding you would have to implement INotifyPropertyChanged on ListingItem.
the magic is not happening. No errors or anything so easy,
Keep an eye on the Output Window during execution. Binding errors are reported.
Made some minor changes to your code as explained below.
class ListingItem
{
public string title { get; set; }
public string user { get; set; }
public string category { get; set; }
//Dummy constructor for test purposes
public ListingItem()
{
title = "TestTitle";
user = "TestUser";
category = "TestCatagory";
}
}
The list item class, I changed the title, user and category to properties (get;set;). I also needed to make them public so they could be accessed through the binding.
class ListMaker
{
public static List getListing()
{
List listing = new List();
for (int i = 0; i < 100; i++)
{
listing.Add(new ListingItem());
}
return listing;
}
}
No changes to your ListMaker class
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute=true)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
I introduced a new class to be able to bind the button. This kind of class if relatively common
<Window x:Class="SimpleDatabinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewmodel="clr-namespace:SimpleDatabinding" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <viewmodel:MainWindowViewModel/> </Window.DataContext> <Grid> <DockPanel> <Button Command="{Binding FillListCommand}" DockPanel.Dock="Top">Fill List</Button> <ListBox ItemsSource="{Binding Listing}" DockPanel.Dock="Top"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <TextBlock Foreground="Gray" Margin="25,0,0,0" Text="{Binding user}"/> <TextBlock Foreground="Gray" Margin="25,0,0,0" Text="{Binding category}"/> </StackPanel> <TextBlock Foreground="Black" Width="270" TextWrapping="Wrap" Text="{Binding title}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </DockPanel> </Grid></Window>
Note the addition of xmlns:viewmodel="clr-namespace:SimpleDatabinding". SimpleDatabinding was the name of the project. It's used to locate the view model in the datacontext below.
The Window.DataContext binds the WPF page to the view model. I called my class MainWindowViewModel (see below). This will automatically create an instance of the view model and bind it to the window.
I introduced a button to click. It's bound to a command FillListCommand. I'll define that in the view model below.
I updated the ItemsSource on the ListBox to be bound to the Listing property.
Other than that, I think it's the same.
class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List Listing { get; set; }
public CommandHandler FillListCommand { get; set; }
public MainWindowViewModel()
{
FillListCommand = new CommandHandler(DoFillList);
}
public void DoFillList()
{
Listing = ListMaker.getListing();
ProperyHasChanged("Listing");
}
private void ProperyHasChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Finally in the viewmodel class, I implemented the INotifyPropertyChanged interface. This is the mechanism to notify the UI that a value on your view model has changed. In most implementations, this is wrapped in some sort of ViewModel base class but I left it in so you could see it.
As above, I converted the Listing variable to a public property (get;set;) so it could be accessed through the binding.
I created a CommandHandler property called FillListCommand. This uses the class above. The button is bound to this variable. The constructor of the view model initializes and points it to the function to be called when the button is clicked.
Finally, in the DoFillList function, I initialize Listing as you had it but I also use the notification to let the UI know it's changed.
Sorry about all the writing. Hope this is somewhat helpful. I don't think it's too different from what you had.
Don't forget to decorate your data members and service methods with the appropriate tags.
These short videos are great for learning WCF:
http://channel9.msdn.com/Shows/Endpoint?sort=rating#tab_sortBy_rating
There were only 2 problems with my code, which I found:
The properties were set as private in ListingItem, which Henk
Holterman caught (+1ed)
I wasn't setting ItemSource on the list anywhere.
I didn't need to do any of the other stuff Peter Trenery mentioned at all.