Dynamically bind button commands in Data Template Items
Posted: 12 Jan 2023, 13:20
Hi,
I'm trying to use Data Templates to fill a ListBox. I'm doing this as I want the list to be dynamic.
In addition to static information I want to have a button on each Item in the ListBox. The command of the button I want to assign also dynamically.
Because this is in a Data Template the NoesisEventCommand is null and I can't call NoesisEventCommand.AddListener(...).
How can I achieve this in another way?
Below you can find a shortened version of my code and xaml.
Unity/C# Code:
XAML
I'm trying to use Data Templates to fill a ListBox. I'm doing this as I want the list to be dynamic.
In addition to static information I want to have a button on each Item in the ListBox. The command of the button I want to assign also dynamically.
Because this is in a Data Template the NoesisEventCommand is null and I can't call NoesisEventCommand.AddListener(...).
How can I achieve this in another way?
Below you can find a shortened version of my code and xaml.
Unity/C# Code:
Code: Select all
public class SkinPanelObject {
public NoesisEventCommand _previewSkinButtonCommand;
public NoesisEventCommand PreviewSkinButtonCommand { get => _previewSkinButtonCommand; }
public SkinPanelObject() {
//PreviewSkinButtonCommand.AddListener(PreviewThisSkin()); Does not work
}
public void PreviewThisSkin() {
Preview();
}
}
public class SkinSelection : MonoBehaviour {
private List<SkinPanelObject> _pawnSkinPanels = new List<SkinPanelObject>();
public List<SkinPanelObject> PawnSkinPanels { get => _pawnSkinPanels; }
private void Start() {
InitSkinPanels();
NoesisView view = GetComponent<NoesisView>();
view.Content.DataContext = this;
}
}
Code: Select all
<UserControl x:Class="MyEngineBuilder.SkinSelectionView"
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"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:noesis="clr-namespace:NoesisGUIExtensions;assembly=Noesis.GUI.Extensions"
d:DesignWidth="1280" d:DesignHeight="720"
Focusable="True">
<UserControl.Resources>
<DataTemplate x:Key="SkinPanelTemplate">
<Border Background="SlateGray">
<StackPanel>
<TextBlock Text="Some Text"/>
<Button Content="Preview" Command="{Binding PreviewSkinButtonCommand}"/>
</StackPanel>
</Border>
</DataTemplate>
</UserControl.Resources>
<ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Auto">
<ListBox ItemsSource="{Binding PawnSkinPanels}" ItemTemplate="{StaticResource SkinPanelTemplate}" Focusable="False"/>
</ScrollViewer>
</UserControl>