I am using Mvvm approach in silverlight. where i try to bind a TextBox like this :
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding ViewModelText}" Grid.Row="0"></TextBlock>
</Grid>
where this xaml.cs class behind this xaml is:
public partial class UIeLementRender : UserControl
{
public UIeLementRender()
{
InitializeComponent();
this.DataContext = new ViewModel.TabControlStuffViewModel.uiElementRendererViewModel();
}
}
and viewmodel class is:
public class uiElementRendererViewModel: GenericViewModel
{
private String viewModelText;
public String ViewModelText
{
get
{
return viewModelText;
}
set
{
viewModelText = value;
OnPropertyChanged("ViewModelText");
}
}
public uiElementRendererViewModel()
{
this.viewModelText = "Hii from UIelemnt rendering"; //this updated but below one is never updated.
}
public uiElementRendererViewModel(ProgramVersion pv) //This constructor is called dynamically on abutton click from other view model class but it never updates the viewModelText
{
this.viewModelText = "Hii changed UIelemnt rendering";
this.OnPropertyChanged("ViewModelText");
}
}
Now when i run the code it shows me "Hii from UIelemnt rendering"; (which is correct) but when i press a button from another viewmodel class dynamically, i wan to update the new text on viewModelText to "Hii changed UIelemnt rendering" . Which is not updated even i have done "this.OnPropertyChanged("ViewModelText");" in my second costructor. (it is still has the text of default constructor/without parameter)
How to update this nex text which is obtained dynamically ?
You need to set the actual property, not re-initialize the whole ViewModel:
viewModel.ViewModelText = "Hii changed UIelemnt rendering";
The call to OnPropertyChanged in your constructor is redundant, as that will run before any actual binding happens.
If you -have- to re-initialize the ViewModel, and there's no possible way around this, then you also need to re-initialize the view, or manually set the DataContext of the existing view to the new instance of the ViewModel class.
I've created a few sample files that illustrate how it -could- be done: http://pastebin.com/W6Yh7N6E
I'll try to illustrate how WPF would do the databinding with a short list here:
Create View
Create ViewModel (Instantiate, run constructor, etc.) - This is where the event is currently fired in your own example
Set ViewModel as DataContext (Which in your example never happens anyways)
WPF Updates its bindings with current values (So no need for another PropertyChanged event here)
There's a bunch more stuff happening behind the scenes, but these steps should be sufficient to give you a decent understanding of why the PropertyChanged event wouldn't do anything in a constructor.
When you create a new viewmodel from you button click, you actually have two instances of the viewmodel. The UI however is still bound to the first one, so whatever changes you make in the second, will never appear on the UI. You could set the second instance as new DataContext:
private void OnButtonClick(object sender, EventArgs e)
{
this.DataContext = new ViewModel.TabControlStuffViewModel.uiElementRendererViewModel(/*pass variable here*/);
}
But this is hardly what you actually want. What you should do instead is modify the existing viewmodel object:
private void OnButtonClick(object sender, EventArgs e)
{
var vm = this.DataContext as uiElementRendererViewModel; // Get the current view model and cast it to correct type
vm.ViewModelText = "Enter new text here"; // Update the text
}
Related
Databinding is a difficult concept that I still can't quite grasp despite reading through dozens of topics already.
I want to have a TextBox that would change its text every time a field 'status' is being changed in my code-behind, for debugging purposes.
Here's what I have so far:
public partial class ReviewsControl : UserControl
{
private Status status = MainControl.AppStatus;
public string StatusDisplay
{
get
{
return status.ToString();
}
}
}
And here's my take on the view:
<TextBlock x:Name="StatusBlock" HorizontalAlignment="Left" Margin="10,450,0,0" TextWrapping="Wrap" Text="{Binding StatusDisplay, Source=ReviewsControl, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Height="40" Width="205"/>
The code above doesn't even show anything, let alone do that dynamically. What should I change if I want XAML to detect changes in the in my C# code and change the textbox accordingly?
I too had issues early on. Your view (display to end-users) does not care how or where things come from, you just know what will be exposed in your View Model controller to bind to. To have things updated in your view, the most common is binding and having your view model include the INotifyPropertyChanged interface. This is so you can force raising the event when a property changes, whatever is "listening" for it will update itself..
Simple class, you can just grab from the : INotify, the event exposed to allow things to get registered to, and your method to actually RAISE the event to pass up stream to those listening for changes.
public class SomeBaseClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Once that is done, your going to expose properties in your class by making as public with getter/setters. You don't bind to a field.
public string SomeThingYouWantToExpose {get; set; }
And in your code, however you are getting data, label refresh, whatever, you would set and raise the property-changed
public void GettingSomeData()
{
// … doing something to get / prepare / whatever...
SomeThingYouWantToExpose = "some new label";
// Now raise which the view bound to this property will updated itself
RaisePropertyChanged( "SomeThingYouWantToExpose" );
}
Now, in your view, you would bind to whatever your view model object is and then the property on the class. Don't know if you specifically need the x:Name reference which basically makes this a field in your control. Not necessary in this example unless you are trying to bind other controls in same display as a result of this field..
<TextBlock Height="40" Width="205" Margin="10,450,0,0"
HorizontalAlignment="Left" VerticalAlignment="Top"
DataContext="{Binding YourViewModelObjectName}"
Text="{Binding SomeThingYouWantToExpose}"
TextWrapping="Wrap" />
Hopefully these pieces within your scenario will make sense and move you forward in your project. Any additional clarification, let me know.
CLARIFICATION on the DATA CONTEXT BINDING
The way I have implemented in my apps, I would have a
MyView -- via the visual declaration... be it a window, grid, complex user control with many controls, whatever...
MyDataModel - a class that is used to query data from whatever data source, such as SQL-Server.
MyView_ViewModel - a custom class that has the INotifyPropertyChanged incorporated and where I expose different properties and other objects I want to expose / make available to the view
So, in the MyData_ViewModel, I would create the view and also create my view model. After creating the view, I would set the overall view's DataContext to the "MyView_ViewModel"
public class MyData_ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public void LoadingMyDataAndView()
{
// Controller I use to get whatever data I need from ex: SQL
_myDataModel = new MyDataModel();
// the view / window / control I want to present to users
_myView = new MyView();
// Now, set the data context on the view to THIS ENTIRE OBJECT.
// Now, anything on THIS class made as public can be have a binding
// directly to the control in the view. Since the DataContext is
// set here, I can bind to anything at this level or lower that is public.
_myView.DataContext = this;
}
private MyView _myView;
private MyDataModel _myDataModel;
// such as example exposed property
public string SomeThingYouWantToExpose {get; set; }
public void GettingSomeData()
{
var something = _myDataModel.GetSomeData();
// … doing something to get / prepare / whatever...
SomeThingYouWantToExpose = "some new label";
// Now raise which the view bound to this property will updated itself
RaisePropertyChanged( "SomeThingYouWantToExpose" );
}
}
Hopefully this EXAMPLE shows how the pieces tie together. The view would no longer need the individual DataContext set since the whole view is set, just needs to bind to the individual public property.
Assuming that the TextBlock is a child element of the UserControl, i.e. that
<TextBlock x:Name="StatusBlock" Text="{Binding StatusDisplay}" ... />
is declared in the UserControl's XAML, the Binding's RelativeSource should be set to the parent UserControl like this:
<TextBlock Text="{Binding StatusDisplay,
RelativeSource={RelativeSource AncestorType=UserControl}}" />
Since StatusDisplay is a property of a UserControl, i.e. a DependencyObject, it should be declared as a dependency property:
public partial class ReviewsControl : UserControl
{
public static readonly DependencyProperty StatusDisplayProperty =
DependencyProperty.Register(
nameof(StatusDisplay), typeof(string), typeof(ReviewsControl);
public string StatusDisplay
{
get { return (string)GetValue(StatusDisplayProperty); }
set { SetValue(StatusDisplayProperty, value); }
}
}
My MainWindow has 4 radio buttons. The user has to choose one, then press on a button that opens up a new window. Depending on the radio button selected, I want to change the background that appears in the new window. This is my code:
public partial class Practice : Window
{
public Practice()
{
InitializeComponent();
if (((MainWindow)Application.Current.MainWindow).BinomialRadio.IsChecked == true)
{
}
else if (((MainWindow)Application.Current.MainWindow).HypergeometricRadio.IsChecked == true)
{
}
else if (((MainWindow)Application.Current.MainWindow).PoissonRadio.IsChecked == true)
{
Background = new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "images/poisson_practice_screen.jpg")));
}
else
{
}
}
}
The new window already has a default background that I set in the properties of the XAML code. This code above runs and executes well, but the picture does not change. I found a quick fix, which is basically to remove the background (so that the new window always has a blank background), and then set it every time it opens. Is there any better way to do this?
Thank you to everyone for their help
The reason that the background of the Practice window does not update is because you set its background in the constructor of the window, which only runs when the window is created. In order for it to update, you have to add event handlers on each of the checkboxes for the Checked event and update the background in the handler.
However, the easiest and most recommended way to do this is using data binding. Data binding is a construct in WPF and other frameworks where you declaratively indicate which properties are linked together, so that you don't have to update them manually. No writing tedious event event handlers or keeping track of complicated changes.
Practice.xaml.cs:
public partial class Practice : Window
{
// INotifyPropertyChanged implementation is important!
// Without it, WPF has no way of knowing that you changed your property...
public class PracticeModel : INotifyPropertyChanged
{
private BitmapImage _background;
public BitmapImage Background
{
get => _background;
set { _background = value; PropertyChanged?.Invoke(nameof(Background)); }
}
public event PropertyChangedEventHandler PropertyChanged;
}
public Practice()
{
InitializeComponent();
// DataContext specifies which object the bindings are bound to
this.DataContext = new PracticeModel();
}
}
Practice.xaml:
<Window x:Class="MyApp.Practice" Background="{Binding Background}">
<!-- your content here; all other attributes of Window omitted for brevity -->
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public Practice.PracticeModel PracticeModel { get; set; } = new Practice.PracticeModel();
// ...
public OnButtonClicked(RoutedEventArgs e)
{
var window = new Practice();
// DataContext specifies which object the bindings are bound to
window.DataContext = this.PracticeModel;
window.Show();
}
public OnPoissonRadioChecked(RoutedEventArgs e)
{
PracticeModel.Background = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "images/poisson_practice_screen.jpg"));
}
// likewise for other radio buttons ...
}
MainWindow.xaml:
<Window x:Class="MyApp.MainWindow">
<RadioButton Group="TheButtons" x:Name="BinomialRadio" IsChecked="True" Checked="OnBinomialRadioChecked" />
<RadioButton Group="TheButtons" x:Name="HypergeometricRadio" Checked="OnHypergeometricRadioChecked" />
<RadioButton Group="TheButtons" x:Name="PoissonRadio" Checked="OnPoissonRadioChecked" />
<RadioButton Group="TheButtons" x:Name="TheOtherRadio" Checked="OnTheOtherRadioChecked" />
</Window>
When you change the property on PracticeModel, the PropertyChanged event is fired. This tells WPF that the property has changed, and it automatically updates all of the relevant bindings. This will quickly become very useful when you want to have more than one dynamically updating property. Additionally, data binding can automatically convert from a string or a Uri to an ImageSource, so you might not even need to create the BitmapImage yourself (and if you don't have to, then don't.)
As you might have noticed, there are still event handlers in this code. That's because I didn't want to introduce too much complexity at the same time, and data-binding radio buttons properly can be kind of confusing for someone who is not accustomed to this. I hope this helps!
I have a userControl named SensorControl which I want to bind its dataContext to a viewModel class named SensorModel.
The binding is successful and the initial values of viewModel is visible in the userControl, but the problem is that when I change the viewModel's properties, the userControl does not update, and I have to manually update that (by assigning null to its dataContext and assigning the viewModel again).
Here is a simplified example of my code.
SensorControl.xml:
<UserControl ...[other attributes]... DataContext={Binding Model}>
.
.
.
<Label Content="{Binding Title}"/>
.
.
.
</UserControl>
SensorControl.xml.cs (code-behind):
public partial class SensorControl : UserControl
{
public SensorModel model;
public SensorModel Model
{
get { return model; }
set { model = value; }
}
public SensorControl(SensorModel sm)
{
Model = sm;
}
}
MainWindow.xml.cs:
public partial class MainWindow : Window
{
public SensorModel sensorModel_1;
public SensorControl sensorControl_1;
public MainWindow()
{
InitializeComponent();
sensorModel_1 = new SensorModel(...[some arguments]...);
sensorControl_1 = new SensorControl(sensorModel_1);
mainGrid.Children.Add(sensorControl_1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
sensorModel_1.Title = "myTitle";
//The UserControl does not update
}
0) I implemented INotifyPropertyChanged in SensorModel
1) The reason I need this, is that there is only one single concept of 'Sensor' in my project (it is a real electronic sensor) and therefore I have a single model for it (that deal with the real sensor, the database, etc), but in the UI I have multiple userControls for presenting different aspects of Sensor. So I have to create one instance of model (SensorModel) for each real sensor, and multiple userControls must bind to that (each one uses different parts of model).
2) I'm not that new to WPF, but I'm kind of new to MVVM and it's possible that I misunderstand something essential, so I would appreciate if someone could clearly explain the correct approach.
Thanks in advance
In your UserControl, remove the DataContext attribute and add an x:Name attribute. Then in your Label, bind like this:
<UserControl x:Name="uc">
<Label Content="{Binding ElementName=uc,Path=Model.Title}" />
</UserControl>
I believe the issue is the DataContext can't be set to Model because binding works off the parent's DataContext which will be based on mainGrid when it gets added as a child to that. Since the property "Model" doesn't exist in maiGrid's DataContext no binding will occur so your update won't reflect. Getting the DataContext of a UserControl properly can be tricky. I use the ElementName quite a bit or create DependencyProperties on the UserControl and then set them from the parent who will be using the control.
You need to set the DataContext to your ViewModel class in your View, and if you're applying the MVVM pattern, you should use ICommand for actions. Maybe it would be better If you'd implement a MainView class that does the logic in the background instead in the MainWindow class.
public MainWindow()
{
InitializeComponent();
DataContext = new MainView();
// sensorModel_1 = new SensorModel(...[some arguments]...);
// sensorControl_1 = new SensorControl(sensorModel_1);
// mainGrid.Children.Add(sensorControl_1);
}
Your MainView class :
public class MainView {
public SensorControl Control {get; internal set;}
...
}
And in your xaml change the binding :
<Label Content="{Binding Control.Model.Title}"/>
Thanks to all of you guys, I took your advices and finally I found a way.
1) I implemented an event in the SensorModel that fires every time any of properties changes (name ModelChanged)
2) Then as Merve & manOvision both suggested, I declared a dependency property in the SensorControl (of type SensorModel) and bind ui elements to that (Binding Path=Model.Title)
3) Then I used the ModelChanged event of this dependency property in the SensorControl and raise an event (of type INotifyPropertyChanged) so the bindings update their value
It works fine.
This is more of a conceptual question rather than a practical one. I'm just starting to learn the MVVM concept for developing UI , and I've come across a dillema I'm not sure the answer to:
Say I have a main window and a little pop-up window (meaning it's a small window with some UI elements in it). The structure of the program will look something like this:
MainWindow
model <-- MainWindowViewModel.cs <-- MainWindowView.xaml (containing no code-behind)
PopUpWindow (A UserControl)
model <-- PopUpWindowViewModel.cs <-- PopUpWindowView.xaml (containing no code-behind)
*the model is just a bunch of BL classes that are irrelevant for this question.
Now , lets say I want to create a new PopUp window from inside the MainWindowViewModel (or even save an instance of it in a private data-member). What is the correct way of doing so?
The way I see it I can't do something like this :
PopUpWindow pop = new PopUpWindow()
Because it kind of defeats the purpose of abstracting the view from the view model(What if a year from now i'll want to create a better version of the PopUpWindow using the same PopUpWindowViewModel?).
On the other hand , I can't initialize a new instnace of the PopUpWindow using just it's view model (The viewModel as I understand is not supposed to know anything about the view that will use it).
Hope it all makes sense... so what would you do in that situation?
*Just to clarify it further , let's say for argument's sake that the situation I'm describing is a button on the MainWindowView that upon clicking will open a PopUpWindowView.
Thanks in advnace.
I had somewhat a similar dilemma and I'll explain how I solved it.
Let's say you have MainWindow and a SettingsWindow, which you want to display when the SettingsButton is clicked.
You have two respective view models, MainWindowViewModel and SettingsViewModel, which you will be passing as their Window.DataContext properties.
Your MainWindowViewModel should expose an ICommand property named SettingsButtonCommand (or similar). Bind this command to the SettingsButton.Command.
Now your command should invoke something like this:
void OnSettingsButtonClicked()
{
var viewModel = new SettingsViewModel();
var window = new SettingsWindow();
window.DataContext = viewModel;
window.Show();
}
There is a slight issue when you want to use Window.ShowDialog(), because you need to resume execution.
For these cases I have an asynchronous variant of the DelegateCommand:
public sealed class AsyncDelegateCommand : ICommand
{
readonly Func<object, Task> onExecute;
readonly Predicate<object> onCanExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public AsyncDelegateCommand(Func<object, Task> onExecute)
: this(onExecute, null) { }
public AsyncDelegateCommand(Func<object, Task> onExecute, Predicate<object> onCanExecute)
{
if (onExecute == null)
throw new ArgumentNullException("onExecute");
this.onExecute = onExecute;
this.onCanExecute = onCanExecute;
}
#region ICommand Methods
public async void Execute(object parameter)
{
await onExecute(parameter);
}
public bool CanExecute(object parameter)
{
return onCanExecute != null ? onCanExecute(parameter) : true;
}
#endregion
}
You've specifically said that the popup is a UserControl so you can use basic data templating. First create view models for your main window and popup control:
public class MainViewModel : ViewModelBase
{
private PopUpViewModel _PopUp;
public PopUpViewModel PopUp
{
get { return _PopUp; }
set { _PopUp = value; RaisePropertyChanged(() => this.PopUp); }
}
}
public class PopUpViewModel : ViewModelBase
{
private string _Message;
public string Message
{
get { return _Message; }
set { _Message = value; RaisePropertyChanged(() => this.Message); }
}
}
The MainViewModel's PopUp member is initially null, we'll set it to an instance of PopUpViewModel when we want the popup to appear. To do that we create a content control on the main window and set it's content to that member. We also use a data template to specify the type of child control to create when the popup view model has been set:
<Window.Resources>
<DataTemplate DataType="{x:Type local:PopUpViewModel}">
<local:PopUpWindow />
</DataTemplate>
</Window.Resources>
<StackPanel>
<Button Content="Show PopUp" Click="Button_Click_1" HorizontalAlignment="Left"/>
<ContentControl Content="{Binding PopUp}" />
</StackPanel>
I'm doing a big no-no here by creating the view model in the code-behind along with a click handler, but it's just for illustrative purposes:
public partial class MainWindow : Window
{
MainViewModel VM = new MainViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = this.VM;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.VM.PopUp = new PopUpViewModel { Message = "Hello World!" };
}
}
That's it! Click the button, popup window appears underneath it showing the content. Now it may not always be this simple, sometimes you may want to create multiple children on a parent control...in that case you'd set up an ItemsControl, set its panel to a Grid (say) and modify the data templates to set the Margin etc on each element to position them. Or you may not always know what type of view model is going to be created, in which case you need to add multiple data templates for each type you're expecting. Either way you still have good separation of concerns because it is the views that are deciding how to display the content in the view models. The view models themselves still don't know anything about the views and they can be unit-tested etc independently.
I've started an MVVM project and now I'm stucking with correct DataBinding.
My project has:
A UserControl whit a ViewModel as DataContext like:
public partial class TestUserControl: UserControl
{
public TestUserControl()
{
this.DataContext = new TestUserControlViewModel();
}
}
ViewModel code is (BaseViewModel class contains PropertyChangedEventHandler):
public class TestUserControlViewModel : BaseViewModel
{
public KrankenkasseControlViewModel()
{}
public IEnumerable<DataItem> GetAllData
{
get
{
IGetTheData src= new DataRepository();
return src.GetData();
}
}
}
IGetTheData is the interface to DataContext:
public interface IGetTheData
{
IEnumerable<DataItem> GetData();
}
}
and finally the DataRepository code:
public class DataRepository : IGetTheData
{
private TestProjectDataContext dax = new TestProjectDataContext();
public IEnumerable<DataItem> GetData()
{
return (from d in this.dax.TestData
select new DataItem
{
ID = d.ID,
SomeOtherData = d.SomeOtherData
});
}
}
My UserControl has a few TextBoxes, but what's the best way to bind correctly?
Thanks for your help, regards.
EDIT: Binding the data against multiple textboxes
After reading your comment, I will elaborate my example for textboxes.
First important thing is that the ViewModel will model the things in the View, so that the View gets all information it needs in the structure it needs. That means, if you have multiple textboses in the View, you will need multiple string Properties in your ViewModel, one for each textbox.
In your XAML you could have something like
<TextBox Text="{Binding ID, Mode=TwoWay}" />
<TextBox Text="{Binding SomeOtherData, Mode=TwoWay}" />
and in your ViewModel
public class TestUserControlViewModel : BaseViewModel {
private string id;
private string someOtherData;
public TestUserControlViewModel() {
DataItem firstItem = new DataRepository().GetData().First();
this.ID = firstItem.ID;
this.SomeOtherData = firstItem.SomeOtherData;
}
public string ID {
get {
return this.id;
}
set {
if (this.id == value) return;
this.id = value;
this.OnPropertyChangedEvent("ID");
}
}
public string SomeOtherData {
get {
return this.someOtherData;
}
set {
if (this.someOtherData == value) return;
this.someOtherData = value;
this.OnPropertyChangedEvent("SomeOtherData");
}
}
}
Here I assume that in your BaseViewModel there is an OnPropertyChangedEvent method to fire the corresponding event. This tells the View that the property has changed and it must update itself.
Note the Mode=TwoWay in the XAML. This means, that it doesn't matter on which side the value changes, the other side will reflect the change immediately. So if the user changes a value in a TwoWay bound TextBox, then the corresponding ViewModel property will automatically change! And also vice versa: if you change the ViewModel property programmatically, the View will refresh.
If you want to show multiple textboxes for more than one data item, then you must introduce more Properties in the ViewModel and bind them accordingly. Maybe a ListBox with a flexible number of TextBoxes inside is a solution then, like #Haspemulator already answered.
Binding the data against a collection control
In the TestUserControl I guess you have a control (like a ListView) to show the list of loaded things. So bind that control against the list in the ViewModel with
<ListView ... ItemsSource="{Binding GetAllData}" ... />
First you must understand that Binding means not "read the data and then forget the ViewModel". Instead you bind the View to the ViewModel (and its Properties) as long as the View lasts. From this point of view, AllData is a much better name than GetAllData (thanks #Malcolm O'Hare).
Now in your code, every time the View reads the AllData property, a new DataRepository is created. Because of the Binding, that is not what you want, instead you want to have one instance of DataRepository for the whole lifetime of the View, which is used to read the initial data and can later be used to update the View, if the underlying database changes (maybe with an event).
To enable such a behavior you should change the type of the AllData property to an ObservableCollection, so that the View can automatically update the list if changes occur.
public class TestUserControlViewModel : BaseViewModel
private ObservableCollection<DataItem> allData;
public TestUserControlViewModel() {
IGetTheData src = new DataRepository();
this.allData = new ObservableCollection<DataItem>(src.GetData());
}
public ObservableCollection<DataItem> AllData {
get {
return this.allData;
}
}
public void AddDataItem(DataItem item) {
this.allData.Add(item);
}
}
Now if you call AddDataItem later, the ListView will update itself automatically.
Your Property Name is bad. You should call it AllData, not GetAllData.
Since you are returning a collection, you probably should be using some sort of list control (ListBox, ListView).
In that case you'd be doing
<ListBox ItemsSource="{Binding GetAllData}" />
Guten Abend. :) As it already mentioned, since you're returning the collection, it's better to use a ListBox. The comment about having ObservableCollection as a cache is also absolutely valid. I would add that if you need to have your data editable, you should use TextBox inside the ItemTemplate:
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text={Binding SomeOtherData,Mode=TwoWay} />
</DataTemplate>
</ListBox.ItemTemplate>
In this case if user edits the text in the box, data will be updated in your data object, so that it could be saved in the database later.