Anyone tried to bind a MediaPlaybackList to ListView?This is the code :
VM
public MediaPlaybackList ObservableMedia
{
get { return _mediaPbList; }
set
{
_mediaPbList = value;
OnPropertyChanged();
}
}
MediaPlaybackList is already a collection so i don't want to use ObservableList<MediaPlaybackList>. Now i'd like to bind this to the ListView :
<ListView x:Name="songList" HorizontalAlignment="Left" Height="680" Background="{Binding }" ItemsSource="{Binding ObservableMedia , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged}" Margin="986,120,0,-80" VerticalAlignment="Top" Width="294">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Items}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The problem is i dont know what property to bind in here <TextBlock Text="{Binding Items}"/> to display title/artist for each mediaPlaybackItem in MediaPlaybackList ?
EDIT : Before i used ObservableCollection<StorageFile> ,that i add to the ListView and it works , but isn't it better if i have just MediaPlaybackList bind? This is how i use the MediaPlaybackList :
mediaSource = MediaSource.CreateFromStorageFile(item);
var mediaPlaybackItem = new MediaPlaybackItem(mediaSource);
ObservableMedia.Items.Add(mediaPlaybackItem);
mediaElement.SetPlaybackSource(ObservableMedia);
So before i'd just have ObservableCollection<StorageFile> listOfStorageFiles
and add listOfStorageFiles.Add(item); , then use this in the xaml and DisplayName , but should i really use additional list(for storageFiles) or somehow make it work with just MediaPlaybackList ?
Related
I am new to xamarin and trying to display a listview. My attempt is as follows.
<ContentPage.Content>
<StackLayout>
<ListView x:Name="ComListView" RowHeight="80">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid Margin="8">
<Label Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="2" Text="hello world" FontAttributes="Bold" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
But when I ran the app, even I navigate to correct page; nothing display. For any other views, it will display the right output. So where could I get wrong on the listview?
You have to put items to the ListView. Currently, you only specify the ItemTemplate, which determines how an item will look (in your case, they will all look the same (i.e. Labels with 'hello world' text)). But the ListView is empty and so there are no items to show.
You can set items using the ItemsSource property of the ListView.
Usually, you use Binding inside an ItemTemplate to show item content.
Let's say we have a class Person:
class Person
{
public string Name { get; set; }
}
Then you create a List of Person objects and add it to your ListView in code:
var personnel = new List<Person>
{
new Person { Name = "Booker" },
new Person { Name = "Elizabeth" }
};
ComListView.ItemsSource = personnel;
And in your XAML, you have to set the ItemTemplate so that it shows the Name of each Person:
<Label Text="{Binding Name, Mode=OneWay}" />
Note: You can also bind to ItemsSource from XAML if you have a ViewModel.
You are not binding the data to the listview.
use the ItemSource property to bind data, either from xaml, code behind or use a binding to populate from your ViewModel
I'm based on the official Microsoft sample to create a MasterDetail ListView:
MasterDetail ListView UWP sample
I have adapted it to my case, as I want that users can edit directly selected items from the ListView. But I meet a strange comportement:
when I add a new item to the ListView, the changes of the current item, done in the details container, are well saved
but when I select an existing item in the ListView, the changes of the current item, done in the details container, are not saved
Here is a screenshot of my app:
The XAML of my ListView is like this:
<!-- Master : List of Feedbacks -->
<ListView
x:Name="MasterListViewFeedbacks"
Grid.Row="1"
ItemContainerTransitions="{x:Null}"
ItemTemplate="{StaticResource MasterListViewFeedbacksItemTemplate}"
IsItemClickEnabled="True"
ItemsSource="{Binding CarForm.feedback_comments}"
SelectedItem="{Binding SelectedFeedback, Mode=TwoWay}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.FooterTemplate>
<DataTemplate>
<CommandBar Background="White">
<CommandBar.Content>
<StackPanel Orientation="Horizontal">
<AppBarButton Icon="Add" Label="Add Feedback"
Command="{Binding AddItemFeedbacksCommand}" />
<AppBarButton Icon="Delete" Label="Delete Feedback"
Command="{Binding RemoveItemFeedbacksCommand}" />
</StackPanel>
</CommandBar.Content>
</CommandBar>
</DataTemplate>
</ListView.FooterTemplate>
</ListView>
The XAML of the ListView's ItemTemplate is:
<DataTemplate x:Key="MasterListViewFeedbacksItemTemplate" x:DataType="models:Feedback_Comments">
<StackPanel Margin="0,11,0,13"
Orientation="Horizontal">
<TextBlock Text="{x:Bind creator }"
Style="{ThemeResource BaseTextBlockStyle}" />
<TextBlock Text=" - " />
<TextBlock Text="{x:Bind comment_date }"
Margin="12,1,0,0" />
</StackPanel>
</DataTemplate>
The XAML of the Details container is like this:
<!-- Detail : Selected Feedback -->
<ContentPresenter
x:Name="DetailFeedbackContentPresenter"
Grid.Column="1"
Grid.RowSpan="2"
BorderThickness="1,0,0,0"
Padding="24,0"
BorderBrush="{ThemeResource SystemControlForegroundBaseLowBrush}"
Content="{x:Bind MasterListViewFeedbacks.SelectedItem, Mode=OneWay}">
<ContentPresenter.ContentTemplate>
<DataTemplate x:DataType="models:Feedback_Comments">
<StackPanel Visibility="{Binding FeedbacksCnt, Converter={StaticResource CountToVisibilityConverter}}">
<TextBox Text="{Binding creator, Mode=TwoWay}" />
<DatePicker Date="{Binding comment_date, Converter={StaticResource DateTimeToDateTimeOffsetConverter}, Mode=TwoWay}"/>
<TextBox TextWrapping="Wrap" AcceptsReturn="True" IsSpellCheckEnabled="True"
Text="{Binding comment, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ContentPresenter.ContentTemplate>
<ContentPresenter.ContentTransitions>
<!-- Empty by default. See MasterListView_ItemClick -->
<TransitionCollection />
</ContentPresenter.ContentTransitions>
</ContentPresenter>
The "CarForm" is the main object of my ViewModel. Each CarForm contains a List of "Feedback_Comments".
So in my ViewModel, I do this when I add a new comment:
private void AddItemFeedbacks()
{
FeedbacksCnt++;
CarForm.feedback_comments.Add(new Feedback_Comments()
{
sequence = FeedbacksCnt,
creator_id = user_id,
_creator = username,
comment_date = DateTime.Now
});
SelectedFeedback = CarForm.feedback_comments[CarForm.feedback_comments.Count - 1];
}
=> the changes done in the Feedback_Comment that was edited before the add are well preserved
I don't do anything when the user select an existing Feedback_Comment: this is managed by the XAML directly.
=> the changes done in the Feedback_Comment that was edited before to select anoter one are not preserved
=> Would you have any explanation?
The TwoWay binding for the Text property is updated only when the TextBox loses focus. However, when you select a different item in the list, the contents of the TextBox are no longer bound to the original item and so are not updated.
To trigger the update each time the Text contents change, so that the changes are reflected immediately, set the UpdateSourceTrigger set to PropertyChanged:
<TextBox Text="{Binding comment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Triggering changes everywhere
To ensure your changes are relflected everywhere including the list, you will need to do two things.
First, your feedback_comments is of type ObservableCollection<Feedback_Comments>. This ensures that the added and removed items are added and removed from the ListView.
Second, the Feedback_Comments class must implement the INotifyPropertyChanged interface. This interface is required to let the user interface know about changes in the data-bound object properties.
Implementing this interface is fairly straightforward and is described for example on MSDN.
The quick solution looks like this:
public class Feedback_Comments : INotifyPropertyChanged
{
// your code
//INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged( [ CallerMemberName ]string propertyName = "" )
{
PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
}
Now from each of your property setters call OnPropertyChanged(); after setting the value:
private string _comment = "";
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value;
OnPropertyChanged();
}
}
Note, that the [CallerMemberName] attribute tells the compiler to replace the parameter by the name of the caller - in this case the name of the property, which is exactly what you need.
Also note, that you can't use simple auto-properties in this case (because you need to call the OnPropertyChanged method.
Bonus
Finally as a small recommendation, I see you are using C++-like naming conventions, which does not fit too well into the C# world. Take a look at the recommended C# naming conventions to improve the code readability :-) .
I made some ExpanderViews and hardcoded everything. That worked and looked nice so I wanted to clean up and only write one ExpanderView in xaml and load everything else with a binding.
As far as I understood I need a ListBox around the whole thing to make it more dynamic?
This is my code so far:
<ListBox ItemsSource="{Binding ContactDe}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<toolkit:ExpanderView Header="{Binding}"
ItemsSource="{Binding LocationName}"
IsNonExpandable="False">
<toolkit:ExpanderView.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding LocationName}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" LineHeight="{StaticResource LongListSelectorGroupHeaderFontSize}" />
</DataTemplate>
</toolkit:ExpanderView.HeaderTemplate>
<toolkit:ExpanderView.ExpanderTemplate>
<DataTemplate>
<TextBlock Text="test" />
</DataTemplate>
</toolkit:ExpanderView.ExpanderTemplate>
<toolkit:ExpanderView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Information}" />
</DataTemplate>
</toolkit:ExpanderView.ItemTemplate>
</toolkit:ExpanderView>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The ContactViewModel-Class:
public class ContactDeViewModel : INotifyPropertyChanged
{
private string _locationName;
public string LocationName
{
get
{
return _locationName;
}
set
{
if (value != _locationName)
{
_locationName = value;
NotifyPropertyChanged("LocationName");
}
}
}
private List<string> _information;
public List<string> Information
{
get
{
return _information;
}
set
{
if (value != _information)
{
_information = value;
NotifyPropertyChanged("Information");
}
}
}
}
And this is where I fill the ContactViewModel:
this.ContactDe.Add(new ContactDeViewModel()
{
LocationName = "Stuttgart",
Information = new List<string>
{
"some text"
}
}
);
this.ContactDe.Add(new ContactDeViewModel()
{
LocationName = "Böblingen",
Information = new List<string>
{
"more text"
}
}
);
I made a SampleViewModel-File where I have:
<vm:MainViewModel.ContactDe>
<vm:ContactDeViewModel LocationName="Location 1" />
<vm:ContactDeViewModel LocationName="Location 2" />
</vm:MainViewModel.ContactDe>
In the preview-window it shows me 2 ExpanderViews with Location 1 and 2. But the same code doesn't work with the emulator or a real device. I don't really understand which Binding-Acces does what. It would already help me a lot if I could see a full example. I googled many tutorials but most only show 1 side, like a xaml without seing how the data is stored.
edit:
Now I edited the viewModel, so it's not a List<string> but a List<Info> with Info only containing string Text. So now I can say ItemsSource="{Binding Text}" which should be only 1 string at a time, right?
As stated in comment to #dellywheel's answer, that you set DataContext this way :
d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
that set DataContext for use in design-time only, hence it doesn't work in run-time. To set DataContext with similar approach for use in run-time, you can try this way :
<ListBox ItemsSource="{Binding ContactDe}">
<ListBox.DataContext>
<vm:MainViewModel/>
</ListBox.DataContext>
........
........
</ListBox>
or this way to set DataContext in page level :
<phone:PhoneApplicationPage>
<phone:PhoneApplicationPage.DataContext>
<vm:MainViewModel/>
</phone:PhoneApplicationPage.DataContext>
........
........
</phone:PhoneApplicationPage>
Another suggestion, prefer ObservableCollection rather than List for use along with data binding. ObservableCollection automatically notify view to refresh whenever item added to or removed from collection.
You need to change your bindings slightly
<toolkit:ExpanderView Header="{Binding LocationName}"
ItemsSource="{Binding Information}"
IsNonExpandable="False">
<toolkit:ExpanderView.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{StaticResource honeFontFamilySemiBold}" LineHeight="{StaticResource LongListSelectorGroupHeaderFontSize}" />
</DataTemplate>
</toolkit:ExpanderView.HeaderTemplate>
<toolkit:ExpanderView.ExpanderTemplate>
<DataTemplate>
<TextBlock Text="test" />
</DataTemplate>
</toolkit:ExpanderView.ExpanderTemplate>
<toolkit:ExpanderView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</toolkit:ExpanderView.ItemTemplate>
</toolkit:ExpanderView>
Hope that helps
I am trying to databind to the combobox. Data is coming from a database table which name is tbltest and table has 2 fileds id and name.
When I am trying to bind name to combox it display me tbltest:name in View. I am using domain services and MVVM to bind data.
Below is my code of ViewModel:
public ViewModel()
{
var query = context.GetTblTestsQuery();
var load = context.Load(query);
load.Completed += (s, ea) =>
{
ObsCompanyCollection = new ObservableCollection<tblTest>(context.tblTests);
};
}
private ObservableCollection<tblTest> _ObsCompanyCollection = new ObservableCollection<tblTest>();
public ObservableCollection<tblTest> ObsCompanyCollection
{
get
{
return _ObsCompanyCollection;
}
set
{
if (_ObsCompanyCollection != value)
{
_ObsCompanyCollection = value;
NotifyPropertyChanged("ObsCompanyCollection");
}
}
}
and Below is code of my XAml file:
<UserControl.Resources>
<my:ViewModel x:Key="ViewModel"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}">
<ComboBox Height="23" HorizontalAlignment="Left" Margin="47,128,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" DisplayMemberPath="{Binding name,Mode=TwoWay}" ItemsSource="{Binding ObsCompanyCollection,Mode=TwoWay}" SelectedItem="{Binding tbldata.SelectCompanyId,Mode=TwoWay}" />
I dont know what is wrong with this code. I want only name to display in my combobox.
Thanks
try this
<ComboBox Height="23" HorizontalAlignment="Left" Margin="47,128,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" ItemsSource="{Binding ObsCompanyCollection,Mode=OneWay}"
I have a combobox in datagrid.I use Silverlight 4.0 and MVVM.
My code works fine,unless when I removed a record from datagrid and add another one, the SelectedValue binding for combobox in added row doesnt work.
<sdk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items, Mode=TwoWay}" Name="dataGrid2" >
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Width="50*">
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=Products, Mode=OneWay}"
SelectedValue="{Binding Path=ProductId,Mode=TwoWay}"
DisplayMemberPath="ProductTitle"
SelectedValuePath="ProductId"/>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
Thanks
Found this piece of code on some site, it helped me in a similar Situation:
public class ComboBoxEx : ComboBox
{
protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var bindingExpression = GetBindingExpression(SelectedValueProperty);
base.OnItemsChanged(e);
if (bindingExpression != null)
{
var binding = bindingExpression.ParentBinding;
SetBinding(SelectedValueProperty, bindingExpression.ParentBinding);
}
}
}