I'm trying to fill my Combobox ItemsSource using Binding in Xaml with a collection of data ObservableCollection but I always get the Combobox ItemsSource null .
WPF UserControl Cs Code : ( Update the code )
public ObservableCollection<User> users { get; set; }
public partial class MainWindow : Window
{
InitializeComponent();
User user1 = new User("Mariah", 15);
User user2 = new User("John", 19 );
users = new ObservableCollections<User>();
users.Add(user1);
users.Add(user2);
this.DataContext = this;
Console.WriteLine(ComboBoxUsers.Items.Count); // always 0
Console.WriteLine(ComboBoxUsers.ItemsSource); // always null
}
WPF UserControl Xaml Code : ( Updated my code )
<ComboBox SelectedIndex = "0" x:Name="ComboBoxUsers" ItemsSource="{Binding users, UpdateSourceTrigger=PropertyChanged}" FontFamily="Arial" FontSize="11" Grid.Row="3" Height="30" Margin="10,5,5,5">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Image IsEnabled="False" Source="{Binding Image}"/>
<TextBlock x:Name="textblock" IsEnabled="False" Text="{Binding Name} />
</StackPanel>
<DataTemplate.Resources>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnable" Value="{Binding IsEnable}"/>
</Style>
</DataTemplate.Resources>
</DataTemplate>
</ComboBox.ItemTemplate>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<Setter
Property="Visibility"
Value="{Binding IsHidden}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
Class User
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public User(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
What is the source of this problem?
Discarding unnecessary (which is not relevant to the question or has syntax errors), your example with a little formatting works fine.
XAML:
<ComboBox x:Name="ComboBoxUsers"
ItemsSource="{Binding Users}"
FontFamily="Arial"
FontSize="11"
Grid.Row="3"
Height="30"
Margin="10,5,5,5">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock IsEnabled="False"
Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Code-behind:
public class User
{
public string Name { get; }
public int Age { get; }
public User(string name, int age)
{
Name = name;
Age = age;
}
}
public partial class MainWindow : Window
{
public ObservableCollection<User> Users { get; }
public MainWindow()
{
InitializeComponent();
// Initialize collection with some items
Users = new ObservableCollection<User>
{
new User("Mariah", 15),
new User("John", 19)
};
DataContext = this;
}
}
Result:
Remarks:
Your
Console.WriteLine(ComboBoxUsers.Items.Count); // always 0
Console.WriteLine(ComboBoxUsers.ItemsSource); // always null
because you use Binding. You needn't access ItemsSource or Items.Count through ComboBox - you should use binded collection Users (e.g. Users.Count) to manipulate or get ComboBox content.
EDIT.
About SelectedItem. You should define for yourself, you want use Bindings or work with ComboBox directly.
Binding push you to NOT use ComboBox.SelectedItem/Index/Value whatever. Even not access ComboBoxUsers to get some data. Binding is closely related to, for example, the MVVM Pattern. If you decided to use Bindings - forget about accessing directly to ComboBox or it data properties SelectedItem/Index/Value or similar.
If you use Bindings - you should create a property (e.g. SelectedUser) for SelectedItem (same as you create property Users for your ItemsSource ) and bind to it:
XAML (introducing binding for SelectedItem property and SelectionChanged handler):
<ComboBox x:Name="ComboBoxUsers"
ItemsSource="{Binding Users}"
SelectedItem="{Binding SelectedUser}"
SelectionChanged="OnUserSelectionChanged"
FontFamily="Arial"
FontSize="11"
Grid.Row="3"
Height="30"
Margin="10,5,5,5">
</ComboBox>
Code-behind (introducing property SelectedUser and OnUserSelectionChanged handler):
public partial class MainWindow : Window
{
public ObservableCollection<User> Users { get; }
// Here would be stored your Binded selected item
public User SelectedUser { get; set; }
// And here is your handler when selection changed
private void OnUserSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// SelectedUser property stores selected in ComboBox item,
// so you can use it directly
_ = MessageBox.Show(SelectedUser.Name);
// Even if you wish to get directly - it is possible
// (thanks to #Clemens):
var selectedUser = (sender as ComboBox).SelectedItem as User;
var selectediIndex = (sender as ComboBox).SelectedIndex;
}
public MainWindow()
{
InitializeComponent();
Users = new ObservableCollection<User>
{
new User("Mariah", 15),
new User("John", 19)
};
DataContext = this;
}
}
Repeat same algorithm for each property you wish to Bind (e.g. SelectedIndex):
SelectedIndex="{Binding SelectedUserIndex}"
public int SelectedUserIndex { get; set; }
Result:
Decide for yourself, what you need. Nice modern Bindings or old boring (sender as ComboBox).SelectedItem.
Related
I was struggling to trigger checked function in WPF, but when it comes to code-behind concept it is okay, but I want to get checked button value with MVVM theory. So do you guys have any idea about this? and in the below, there is tried code with code behind theory.
<DataTemplate>
<dc:RadioButton GroupName="DemoRadios1"
Margin="0,0,15,0"
IsEnabled="{Binding RadioIsEnabled}"
IsReadOnly="{Binding RadioIsReadOnly}"
InnerCheckerVisibilityWhenReadOnly="{Binding RadioInnerCheckerVisibilityWhenReadOnly}"
InnerCheckerVerticalAlignment="{Binding RadioInnerCheckerVerticalAlignment}"
IsChecked="{Binding IsChecked}"
Content="{Binding OverridedSettingValueName}"
Checked="RadioButton_Checked"/>
</DataTemplate>
#Code behind function
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
// ... Get RadioButton reference.
var button = sender as RadioButton;
// ... Display button content as title.
var Title = button.Content.ToString();
}
It looks like maybe you have a collection of things you're working with.
RadioButton has a command property, so you could potentially bind a command and commandparameter if this code must be in the window viewmodel.
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<StackPanel>
<TextBlock Text="{Binding RowName}"/>
<ItemsControl ItemsSource="{Binding Rows}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding Name}"
IsChecked="{Binding IsChecked}"
Command="{Binding DataContext.CheckedCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
GroupName="DemoRadios1"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Window>
My viewmodel:
public class MainWindowViewModel : BindableBase
{
public DelegateCommand<RowVM> CheckedCommand { get; private set; }
public ObservableCollection<RowVM> Rows{ get; set; } = new ObservableCollection<RowVM>(
new List<RowVM>
{
new RowVM{Name="Andrew"},
new RowVM{Name="Bill"},
new RowVM{Name="Carol"},
}
);
private string rowName;
public string RowName
{
get => rowName;
set { SetProperty(ref rowName, value); }
}
public MainWindowViewModel()
{
CheckedCommand = new DelegateCommand<RowVM>((row) =>
{
if(!row.IsChecked)
{
return;
}
RowName = row.Name;
});
}
My RowVM lacks any raising of property changed.
public class RowVM : BindableBase
{
public string Name { get; set; }
public bool IsChecked { get; set; } = false;
}
I'm guessing this datatemplate is used for a collection so there will be an itemscontrol with an itemssource bound to a collection of row viewmodels.
This is somewhat simpler if you can instead have code in the viewmodel for a row.
You already bound IsChecked.
You can therefore just put some code in the set accessor if that bound IsChecked property of your viewmodel:
public class RowViewModel : BindableBase
{
private bool isChecked;
public bool IsChecked
{
get => isChecked;
set
{
isChecked = value;
DoStuff(value);
RaisePropertyChanged();
}
}
Problem: When location is changed via ComboBox cb1 the related location TextBlock does not change to updated value.
I am self learning and below is experiment code on binding that has
public EmpDeptViewModel vm; its initialize on button click event as below
private void btn2_Click(object sender, RoutedEventArgs e) {
vm = new EmpDeptViewModel();
this.Bindings.Update(); }
The XAML looks like this.
<ListView x:Name="listview3" ItemsSource="{x:Bind vm.InstanceOfDepartmentData}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="classes:Department">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5">
<Run Text="DeptNo: " /><Run Text="{x:Bind DeptNo}" />
</TextBlock>
<TextBlock Margin="5">
<Run Text="DeptName: " /><Run Text="{x:Bind DeptName}" />
</TextBlock>
<TextBlock Margin="5">
<Run Text="Location: " /><Run Text="{x:Bind Location, Mode=OneWay}" />
</TextBlock>
<ComboBox x:Name="cb1" ItemsSource="{Binding Source={StaticResource MyLocatonList}, Path=ListofLocationsInsideViewModel, Mode=TwoWay}" DisplayMemberPath="LocationName" SelectedValuePath="LocationName" SelectedValue="{x:Bind Location}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Problem: When location is changed via ComboBox cb1 the related location TextBlock does not change to updated value.
The x:DataType="classes:Department" looks like this.
public class Department : BindableBase
{ private string _location;
public Department(int pdeptNo, string pdeptName, string plocation)
{
DeptNo = pdeptNo;
DeptName = pdeptName;
Location = plocation;
ListOfDeparmentEmployees = new List<Employee>(); }
public int DeptNo { get; set; }
public string DeptName { get; set; }
public string Location {
get { return this._location; }
set { this.SetProperty(ref this._location, value); }
}
public List<Employee> ListOfDeparmentEmployees { get; set; }
}
You may be bound in the wrong position
In your ComboBox, you set TwoWay to the ItemsSource. This does not make sense. You cannot change the Location if you modify the value of the ComboBox.
Try this:
Xaml
...
<ComboBox x:Name="cb1" ItemsSource="{Binding Source={StaticResource MyLocatonList}, Path=ListofLocationsInsideViewModel}"
DisplayMemberPath="LocationName" SelectedValuePath="LocationName" SelectedValue="{x:Bind Location,Mode=TwoWay}" />
...
However, if you write it directly, it will cause an endless loop and then report an error. You need to rewrite the Location property of the Department class.
Department.cs
...
public string Location
{
get { return this._location; }
set
{
if (_location != value)
{
this.SetProperty(ref this._location, value);
}
}
}
...
In addition, please note whether your BindableBase base class implements the INotifyPropertyChanged interface, which is the basis for modifying the UI while modifying the data.
Best regards.
I want to implement somekind of messaging communciation (I know how to use messaging of MVVM.Light) but I think my case is trickier, because I'm using the CommandParameter to change ViewModel, I can't add the command I want :x to the code to become more clear.
XAML
<ListView x:Name="dataGrid" ItemsSource="{Binding Friends}" Height="314" BorderThickness="0" SelectedItem="{Binding SelectedItemFriends}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="Resources\Images\ic_status.png" Height="24" Width="18"/>
<StackPanel Margin="5" Orientation="Vertical">
<TextBlock FontWeight="Bold" Text="{Binding name}"/>
<StackPanel x:Name="RemoveItems" Margin="5" Orientation="Vertical">
<TextBlock Text="{Binding lastLocation}"/>
<TextBlock Text="{Binding timestamp}"/>
</StackPanel>
<StackPanel x:Name="AdditionItems" Margin="5" Orientation="Vertical" Visibility="Collapsed">
<TextBlock Text="{Binding Path=loc.area}"/>
<TextBlock Text="{Binding Path=loc.building}"/>
<TextBlock Text="{Binding Path=loc.floor}"/>
<TextBlock Text="{Binding Path=loc.room}"/>
</StackPanel>
</StackPanel>
<Button Style="{DynamicResource FlatButtonStyle}" Command="{Binding DataContext.SelectViewCommand, ElementName=GeneralWindowView}" CommandParameter="ChatViewModel" x:Name="button1" Content="Chat" Margin="10">
<Button.Template>
<ControlTemplate>
<Image Source="Resources\Images\chat_image.png"/>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" Value="true">
<Setter TargetName="AdditionItems" Property="Visibility" Value="Visible"/>
<Setter TargetName="RemoveItems" Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
So I am in the FriendsViewModel (is a child of GeneralViewModel) and I want to send information to the ChatViewModel (also a child of GeneralViewModel). The thing is where can I fire the command ? Because I'm using the Command Parameter, I can't implement other command :x and use messenger.
Thanks in advance,
EDIT: AViewModel
public abstract class AViewModel : ViewModelBase
{
//public WindowService ws;
public string Name { get; set; }
public RelayCommand<string> SelectViewCommand { get; set; }
public AViewModel()
{
//ws = new WindowService();
SelectViewCommand = new RelayCommand<string>(OnSelectViewCommand);
}
private static ObservableCollection<ViewModelBase> _ViewModels;
public static ObservableCollection<ViewModelBase> ViewModels
{
get { return _ViewModels; }
set { _ViewModels = value; }
}
public void AddViewModel(ViewModelBase viewmodel)
{
if (ViewModels == null)
ViewModels = new ObservableCollection<ViewModelBase>();
var currentVNs = (from vms in ViewModels where vms.InternalName == viewmodel.InternalName select vms).FirstOrDefault();
if (currentVNs == null)
ViewModels.Add(viewmodel);
}
public ViewModelBase GetViewModel(string viewmodel)
{
return ViewModels.FirstOrDefault(item => item.InternalName == viewmodel);
}
public ViewModelBase GetViewModelLogin(string viewmodel,object bla)
{
return ViewModels.FirstOrDefault(item => item.InternalName == viewmodel);
}
private void OnSelectViewCommand(string obj)
{
switch (obj)
{
case "ExitCommand":
Application.Current.Shutdown();
break;
default:
this.Current_ViewModel = this.GetViewModel(obj);
break;
}
}
private ViewModelBase _Current_ViewModel;
private IMessenger _messengerInstance;
public ViewModelBase Current_ViewModel
{
get { return _Current_ViewModel; }
set { _Current_ViewModel = value; OnPropertyChanged("Current_ViewModel"); }
}
protected IMessenger MessengerInstance
{
get
{
return this._messengerInstance ?? Messenger.Default;
}
set
{
this._messengerInstance = value;
}
}
}
If you remember in my last demo I was raising an 'Event' in the setter of property 'Current_ViewModel' in AviewModel that gets fired every time you navigate to a different View. Well, after thinking about it I had the idea that the Event can also send an object [to the new ViewModel\View] also....
you need to use the 'CommandParameter' class tho...
public enum Command
{
None,
LogIn,
LogOut,
Recovery,
Register,
Exit
}
public class CommandParameter
{
public dynamic Obj { get; set; }
public Command Command { get; set; }
public string Link_1 { get; set; }
public string Link_2 { get; set; }
}
example usage...
this.LogInCommandParameter = new CommandParameter() { Obj = this.CurrentUser, Command = Command.LogIn, Link_1 = "Main_ViewModel", Link_2 = "LogOnError_ViewModel" };
in the above code
Obj = the object you want to send onto you next View
Command = is a 'hint' that you can Switch on in your Buttons bound Command
Link_1 & Link_2 are the Views that you want to Navigate too....
there is a lot more to it than that so I have attached another demo here http://www.mediafire.com/download/5ttjhuiuxex7eo1/Navigation1_25-05.rar (file size is quite big now because the Demo uses EF and there is a web service too.... should all work from VS IDE tho)
you'll see in AviewModel
private ViewModelBase _Current_ViewModel;
public ViewModelBase Current_ViewModel
{
get { return _Current_ViewModel; }
set {
if (Current_ViewModel != null)
Current_ViewModel.RaiseDeActivate(SendObject);
_Current_ViewModel = value;
if (Current_ViewModel != null)
Current_ViewModel.RaiseActivate(SendObject);
OnPropertyChanged("Current_ViewModel"); }
}
I am now raising two events (DeActivate and Activate) and also note that I am sending a param called SendObject (this is your Obj in CommandParameter)...
in the ViewModel you simply subscribe to the Events like so....
// in the constructor....
this.Activate += Main_ViewModel_Activate;
this.DeActivate += Main_ViewModel_DeActivate;
private void Main_ViewModel_DeActivate(object sender, ActivateArgs e)
{
}
private void Main_ViewModel_Activate(object sender, ActivateArgs e)
{
// e.Data will be the SendObject from AviewModel
}
Have a look\step though at the Demo code... you'll see that (after creating a new user to log on with) once you log on with a valid UserName\Password, that 'User' (the entire 'User' Object) is passed FROM LogOn_ViewModel TO Main_ViewModel VIA the OnWindowCommand in Base_ViewModel... the UserName (that you used to log on with in LogOn_View) is then displayed on the Main_View.
I'm trying to get the databinding I need to work with a ListBox.
I've parsed some data from a text file to a ObservableCollection<ViewModel> but the data isn't updating in the ListBox.
Here's some information:
The data which is written to from the parser:
class MainData
{
private static ObservableCollection<GroupViewModel> groupModelList = new ObservableCollection<GroupViewModel>();
public static ObservableCollection<GroupViewModel> GroupModelList
{
get { return groupModelList; }
}
}
What GroupViewModel holds (not everything but it's all the same):
class GroupViewModel : INotifyPropertyChanged
{
private GroupModel groupModel;
public event PropertyChangedEventHandler PropertyChanged;
public GroupViewModel()
{
groupModel = new GroupModel();
}
public string Name
{
get { return groupModel.name; }
set
{
if (groupModel.name != value)
{
groupModel.name = value;
InvokePropertyChanged("Name");
}
}
}
...
}
And what GroupModel Holds:
class GroupModel
{
public string name { get; set; }
}
This is how the parser adds new items to the GroupModelView:
if (split[0] == "group")
{
currentGroup = new GroupViewModel();
currentGroup.Name = split[1];
MainData.GroupModelList.Add(currentGroup);
}
I created a ListBox in my WPF application with these XAML options:
<Window x:Class="SoundManager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:SoundManager.ViewModels"
xmlns:vm2="clr-namespace:SoundManager.Code"
Title="MainWindow" Height="720" Width="1280">
<Window.Resources>
<vm:MainViewModel x:Key="MainViewModel" />
<vm2:MainData x:Key="MainData" />
</Window.Resources>
<ListBox Grid.Row="2" Height="484" HorizontalAlignment="Left" Margin="12,0,0,0" Name="lbFoundItems" VerticalAlignment="Top" Width="201" ItemsSource="{Binding Source={StaticResource MainData}, Path=GroupModelList/Name}" />
but for some reason the data isn't updating in the UI (new items aren't added visibly in the UI).
I've been just getting started with the MVVM pattern and databinding and I can't figure out what I'm doing wrong.
Thanks in advance!
GroupModelList/Name is not a valid property path here. Setting it like that does not make the ListBox show the Name property of the data items in the GroupModelList collection.
You would instead have to set the ListBox's DisplayMemberPath property:
<ListBox ItemsSource="{Binding Source={StaticResource MainData}, Path=GroupModelList}"
DisplayMemberPath="Name"/>
or set the ItemTemplate property:
<ListBox ItemsSource="{Binding Source={StaticResource MainData}, Path=GroupModelList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Moreover, the GroupModelList property should not be static:
class MainData
{
private ObservableCollection<GroupViewModel> groupModelList =
new ObservableCollection<GroupViewModel>();
public ObservableCollection<GroupViewModel> GroupModelList
{
get { return groupModelList; }
}
}
Then you might have MainData as a property in your view model, and bind the ListBox like this:
<ListBox ItemsSource="{Binding Source={StaticResource MainViewModel},
Path=MainData.GroupModelList}" .../>
Hi, I am trying to bind the data for text block within a LongListSelector. But I am not getting any Output for it, kindly help me.
This is my XAML code:
<phone:LongListSelector ItemsSource="{Binding ''}" x:Name="longListSelector" HorizontalAlignment="Left" Height="680" VerticalAlignment="Top" Width="446" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="name" Text="{Binding DataContext.TextContent,ElementName=page,Mode=OneWay}" Height="100" Width="100" HorizontalAlignment="Center">
</TextBlock>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
In the C# code I have parsed data which i need to display in the windows phone, in a menu format.
Part of C# code is shown below:
XDocument document = XDocument.Parse(e.Result);
var data1 = from query in document.Descendants("location")
select new Data
{
Lat = (string)query.Element("lat"),
Lag = (string)query.Element("lng")
};
foreach (var d in data1)
{
JsonParsing(d.Lat, d.Lag);
}
data1 = from query in document.Descendants("result")
select new Data
{
Country = (string)query.Element("formatted_address")
};
foreach (var d in data1)
{
// ob.JsonParsing(d.Lat, d.Lag);
//XmlParsing(d.Lat, d.Lag);
val = d.Country;
//listbox.Items.Add(val);
//StringsList.Add(val);
TextContent=val;
I want the value of the country to be shown inside the textblock, kindly help me figure this out as I am pretty new to this field, thanks.
try like this
a good reference
<DataTemplate>
<StackPanel VerticalAlignment="Top">
<TextBlock Text="{Binding Value}" />
</StackPanel>
</LongListSelector>
CodeBehind
**Add a public property only public property can be participate in databinding**
#region Public Properties
private ObservableCollection<YourModel> _collectionofValue;
public ObservableCollection<YourModel> CollectionofValues
{
get
{
return _collectionofValue;
}
set
{
_collectionofValue=value;
raisepropertyChanged("CollectionofValues");
}
}
private string _value;
public string Value
{
get
{
return _errorMessage;
}
set
{
_errorMessage = value;
RaisePropertyChanged("Value");
}
}
#endregion
**Set value to this public property when you get value**
// for single values
public void getValue()
{
value =GetXmlValue(); // your method that will return the value;
}
// as it is a collection
public void getValuestoCollection()
{
Collection.Add(new YourModel(value="SampleValue1");
Collection.Add(new YourModel(value="SampleValue1");
Collection.Add(new YourModel(value="SampleValue1");
Collection.Add(new YourModel(value="SampleValue1");
}
YourModel
// the collection of this model is binded to the LongListSelector.
public class ModelName
{
public string Values {get;set;}
}
reference
<phone:LongListSelector ItemsSource="{Binding Items}" x:Name="longListSelector" HorizontalAlignment="Left" Height="680" VerticalAlignment="Top" Width="446" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="name" Text="{Binding Path=TextContent}" Height="100" Width="100" HorizontalAlignment="Center">
</TextBlock>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
Your C# algm should be:
i) Have a viewmodel class
public class MyViewModel
{
public ObservableCollection<MyDataItem> Items {get; set;}
public MyViewModel()
{
Items=new ObservableCollection<MyDataItem>();
loop //add your items to your 'Items' property so that you can bind this with LongListSelector ItemsSource
{
Items.Add(new MyDataItem("mystring"));
}
}
}
public class MyDataItem
{
public MyDataItem(string s)
{
TextContent=s;
}
public string TextContent {get;set;}
}
ii) Create an instance to ViewModel class and set DataContext
// write this in the constructor of the page which contains the LongListSelector
public MyViewModel vm;
constructor()
{
vm=new MyViewModel();
this.DataContext=vm;
}