NoesisGUI & Unity3D - Data Binding
Posted: 13 Aug 2014, 22:24
Video tutorial demonstrating how you can bind a ComboBox to an Image control and load the images at runtime just by specifying their filename.
Code: Select all
using UnityEngine;
using System.Collections;
using Noesis;
[Noesis.Extended]
public class Animal: BaseComponent
{
private string name_;
public string Name
{
get { return name_; }
set { name_ = value; NotifyPropertyChanged("Name"); }
}
private ImageSource image_;
public ImageSource Image
{
get { return image_; }
set { image_ = value; NotifyPropertyChanged("Image"); }
}
}
[Noesis.Extended]
public class ViewModel: BaseComponent
{
private Collection collection_;
public Collection Animals
{
get { return collection_; }
set { collection_ = value; NotifyPropertyChanged("Animals"); }
}
public ViewModel()
{
collection_ = new Collection();
}
}
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
var tex0 = new TextureSource(Resources.Load("cat") as Texture2D);
var cat = new Animal { Name = "Cat", Image = tex0 };
var tex1 = new TextureSource(Resources.Load("dog") as Texture2D);
var dog = new Animal { Name = "Dog", Image = tex1 };
var vm = new ViewModel();
vm.Animals.Add(cat);
vm.Animals.Add(dog);
var noesisGUI = GetComponent<NoesisGUIPanel>();
var root = noesisGUI.GetRoot<Grid>();
root.SetDataContext(vm);
}
}
Code: Select all
<Grid
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"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480">
<Grid.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid>
<TextBlock HorizontalAlignment="Left" Height="25" Margin="0,0,-136.54,-5" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="187"/>
</Grid>
</DataTemplate>
</Grid.Resources>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Height="29" VerticalAlignment="Top" Width="241" ItemsSource="{Binding Animals}" ItemTemplate="{DynamicResource DataTemplate1}"/>
<Image HorizontalAlignment="Left" Height="199" Margin="0,34,0,0" VerticalAlignment="Top" Width="232" Source="{Binding SelectedItem.Image, ElementName=comboBox}"/>
</Grid>