I have a GridView
<GridView ItemsSource="{x:Bind ViewModel.SoundEffects}">
<GridView.ItemTemplate>
<DataTemplate x:dataType="?">
<Button Style="{StaticResource defaultButton}"
Content="{Binding Name}"
Tag="{Binding FileName}"
Command="{x:Bind ViewModel.PlayCommand}"
CommandParameter="{Binding FileName}"/>
</DataTemplate>
</GridView.ItemTemplate>
Whenever I try to compile it, it says I need to specify a model, but I can't figure out, how to make model, which contains definition for ViewModel, when I tried to create an interface:
public interface ISoundEffectButton
{
string Name { get; }
string FileName { get; }
ViewModels.MainPageViewModel ViewModel { get; }
}
But this didn't work and crashed the whole debugger.
Thanks for your time.
Inside a DataTemplate (whether used as an item template, a content template, or a header template), the value of Path is not interpreted in the context of the page, but in the context of the data object being templated. So that its bindings can be validated (and efficient code generated for them) at compile-time, a DataTemplate needs to declare the type of its data object using x:DataType.
So first, you need to make you model like this:
public class SoundEffectButton
{
public string Name { get; set;}
public string FileName { get; set;}
public ICommand Play { get; set; }
}
It is a Class
, not a interface. Then use it in your page like this:
xmlns:data="using:[the namespace of your model]
The x:DataType
of GridView
can be set as following:
<DataTemplate x:DataType="data:SoundEffectButton">
In your ViewModel, you can use a collection for your data:
public ObservableCollection<SoundEffectButton> SoundEffects;
At last, use your ViewModel in the cs file of your page:
public MainPage()
{
this.InitializeComponent();
ViewModel = new MainPageViewModel();
}
public MainPageViewModel ViewModel { get; set; }
The GridView
should be like this:
<GridView ItemsSource="{x:Bind ViewModel.SoundEffects}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:SoundEffectButton">
<Button Style="{StaticResource defaultButton}"
Content="{Binding Name}"
Tag="{Binding FileName}"
Command="{x:Bind Play}"
CommandParameter="{Binding FileName}" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
I wrote a demo here for your problem, you may have a look.