I have indexed Image, like these:
<s:Image id="imgListaTaskAnalysis0" left="20" top="110" width="200" height="200"/>
<s:Image id="imgListaTaskAnalysis1" left="20" top="360" width="200" height="200"/>
<s:Image id="imgListaTaskAnalysis2" left="20" top="360" width="200" height="200"/>
And so on..
I want to put them in an array, so:
public var arrayImg:Array = new Array(imgListaTaskAnalysis0,imgListaTaskAnalysis1,imgListaTaskAnalysis2);
But I can't give them a source:
for(var i:Number=0;i<=arrayImg.length;i++)
arrayImg[i].source = cuboImmagini.path;
In this way doesn't work, doesn't give them any source..There is a way to do this?
It is the interested part of my project:
public var arrayImg:Array = new Array(imgListaTaskAnalysis0,imgListaTaskAnalysis1);
/* DICHIARAZIONE IMMAGINI */
public var cuboImmagini:Object = {path:"../assets/cuboImmagini.png"};
public var exit:Object = {path:"../assets/exit.png"};
public var home:Object = {path:"../assets/home.png"};
/* FINE DICHIARAZIONE IMMAGINI */
/* FUNZIONI */
// cambiaPagina
public function cambiaPagina(prossimaPagina:String):void
{
currentState = prossimaPagina;
}
// chiudiApplicazione
protected function chiudiApplicazione(event:MouseEvent):void
{
NativeApplication.nativeApplication.exit();
}
public function carica():void
{
arrayImg[0].source = cuboImmagini.path;
arrayImg[1].source = home.path;
cambiaPagina("HomePage");
}
/* FINE FUNZIONI */
]]>
</fx:Script>
<s:states>
<s:State name="PaginaPresentazione"/>
<s:State name="HomePage"/>
<s:State name="ListaTaskAnalysis"/>
<s:State name="ScegliAzioneTaskAnalysis"/>
</s:states>
<fx:Declarations>
</fx:Declarations>
<!-- =================================== MXML =================================== -->
<!-- =================================== PaginaPresentazione =================================== -->
<s:Group id="gruppoPaginaPresentazione" includeIn="PaginaPresentazione" left="0" right="0" top="0" bottom="0"
horizontalCenter="0" verticalCenter="0">
<s:Button id="btnPresentazione" right="10" bottom="10" label="INIZIA"
click="carica()"/>
</s:Group>
<!-- =================================== HomePage =================================== -->
<s:Group id="gruppoHomePage" includeIn="HomePage,PaginaPresentazione" left="0" right="0" top="0"
bottom="0" horizontalCenter="0" verticalCenter="0">
<s:Button id="btnVaiTaskAnalysis" includeIn="HomePage" width="600" height="90"
label="TASK ANALYSIS" click="cambiaPagina('ListaTaskAnalysis')" fontSize="50"
horizontalCenter="0" verticalCenter="80"/>
<s:Button id="btnVaiStorieSociali" includeIn="HomePage" width="600" height="90"
label="STORIE SOCIALI" fontSize="50" horizontalCenter="0" verticalCenter="-80"/>
</s:Group>
<!-- =================================== /HomePage =================================== -->
<s:Group id="gruppoListaTaskAnalysis" includeIn="ListaTaskAnalysis" left="0" right="0" top="0" bottom="0"
horizontalCenter="0" verticalCenter="0">
<s:Group id="gruppoBottoniListaTaskAnalyis" left="0" right="0" top="0" height="90"
horizontalCenter="0">
<s:Button id="btnExitListaTaskAnalysis" right="10" top="5" width="80" height="80"
icon="assets/exit.png" click="chiudiApplicazione(event)"/>
<s:Button id="btnHomeListaTaskAnalysis" right="100" top="5" width="80" height="80"
icon="assets/home.png" click = "cambiaPagina('HomePage')"/>
</s:Group>
<s:Image id="imgListaTaskAnalysis0" left="20" top="110" width="200" height="200"
source="assets/cuboImmagini.png"/>
<s:Image id="imgListaTaskAnalysis1" left="20" top="360" width="200" height="200"/>
<s:Button id="btnSegreto1" left="10" bottom="10" width="90" height="90" alpha="0.1" click="combinazioneSegreta(1)"/>
<s:Button id="btnSegreto2" right="10" bottom="10" width="90" height="90" alpha="0.1" click="combinazioneSegreta(2)"/>
</s:Group>
<s:Group id="gruppoListaTaskAnalysis0" includeIn="ScegliAzioneTaskAnalysis" left="0" right="0"
top="0" bottom="0" horizontalCenter="0" verticalCenter="0">
<s:Group id="gruppoBottoniListaTaskAnalyis0" left="0" right="0" top="0" height="90"
horizontalCenter="0">
<s:Button id="btnExitScegliAzioneTaskAnalysis0" right="10" top="5" width="80" height="80"
icon="assets/exit.png" click="chiudiApplicazione(event)"/>
<s:Button id="btnHomeScegliAzioneTaskAnalisys" right="100" top="5" width="80" height="80"
icon="assets/home.png" click = "cambiaPagina('HomePage')"/>
</s:Group>
</s:Group>
<!-- =================================== /HomePage =================================== -->
Thanks in advance..
I solved the problem.. I put the images in the array when they are created:
<s:Image id="img" creationComplete = "loadImage(event,this.img,0) />
---------------------------------------------------------------------
public function loadImage(e:FlexEvent,img:Image,num:Number):void
{
array[num] = img;
}
Thanks anyway..
Related
I encounter a problem that I am not sure how to fix. I have "AddAccount" (Button), "AccountsTextBlock" and a ListBox on the main window. If not user is added, the list box will be hidden, once user is added, it will show the ListBox, AddAccount and AccountsTextBlock on the same screen, but AddAccount and AccountsTextBlock will be at different positions from when there's no user. The problem is that AddAccount and AccountsTextBlock didn't show, but a dotted rectangle shows.
<Grid>
<Canvas>
<TextBlock x:Name="AddAccountTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Height="60" Width="369" Text="Add account to allow for simple access to your company resources
" SnapsToDevicePixels="True" Canvas.Left="38" Canvas.Top="313"/>
<Button x:Name="AddAccount" Content="Add Account" Canvas.Left="145" Canvas.Top="333" HorizontalAlignment="Left" VerticalAlignment="Top" Width="140" RenderTransformOrigin="0.466,0.977" IsCancel="True" Height="40" Foreground="White" Background="Blue" Click="OnAddAccount"/>
<TextBlock x:Name="AccountsTextBlock" Canvas.Left="176" TextWrapping="Wrap" Text="Accounts" Canvas.Top="10" Height="33" Width="68" FontSize="16" FontFamily="Tahoma"/>
</Canvas>
<ListBox x:Name="accounts" HorizontalAlignment="Left" Height="237" VerticalAlignment="Top" Width="444" SelectionChanged="ListBox_SelectionChanged" Background="White" BorderBrush="White" Margin="0,47,0,0" RenderTransformOrigin="0.5,0.5">
<ListBox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform AngleX="0.384"/>
<RotateTransform/>
<TranslateTransform X="-0.794"/>
</TransformGroup>
</ListBox.RenderTransform>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Height" Value="100"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="_Border" BorderBrush="Gray" BorderThickness="0.5"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="_Border" Property="Background" Value="LightSkyBlue"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="0" Grid.Column="0" Width="100" Source="{Binding Path=imagePath}" />
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Path=userInfo}"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
public MainWindow()
{
InitializeComponent();
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(authenticatorRegistryKey))
{
Object valueStr = Registry.GetValue(authenticatorRegistryKey, addedUsersRegistryValueName, null);
if (valueStr == null)
{
//no users added yet, hide list box and move add button
accounts.Visibility = Visibility.Collapsed;
AccountsTextBlock.Visibility = Visibility.Collapsed;
Canvas.SetLeft(AddAccountTextBlock, (Application.Current.MainWindow.Width - AddAccountTextBlock.Width) / 2);
Canvas.SetTop(AddAccountTextBlock, (Application.Current.MainWindow.Height - AddAccountTextBlock.Height) / 2 - AddAccount.Height + 10);
Canvas.SetLeft(AddAccount, (Application.Current.MainWindow.Width - AddAccount.Width) / 2);
Canvas.SetTop(AddAccount, (Application.Current.MainWindow.Height - AddAccount.Height) / 2);
}
else
{
//show the added user
List<UserInfo> items = new List<UserInfo>();
items.Add(new UserInfo()
{
userInfo = "abcdefg",
imagePath = ""
});
accounts.ItemsSource = items;
AccountsTextBlock.Visibility = Visibility.Visible;
accounts.Visibility = Visibility.Visible;
}
}
}
private void OnAddAccount(object sender, RoutedEventArgs e)
{
SignInUrlWindow signInUrlWindow = new SignInUrlWindow();
signInUrlWindow.Left = Application.Current.MainWindow.Left;
signInUrlWindow.Top = Application.Current.MainWindow.Top;
signInUrlWindow.Width = Application.Current.MainWindow.Width;
signInUrlWindow.Height = Application.Current.MainWindow.Height;
signInUrlWindow.ShowDialog();
List<UserInfo> items = new List<UserInfo>();
items.Add(new UserInfo()
{
userInfo = "abcdefg",
imagePath = ""
});
accounts.ItemsSource = items;
accounts.Visibility = Visibility.Visible;
AddAccount.Visibility = Visibility.Visible;
AccountsTextBlock.Visibility = Visibility.Visible;
}
I have a WPF XAML page, having 3 sections separated by DockPanels. One panel contains an INFRAGITICS XamDataGrid control to be bound with a collection.
I would like to bind XamDataGrid control using DataContext/DataSource property in pure MVVM way.
Also, would be delighted to understand if binding is done through dependency injection.
I have tried different approaches but didn't get success. I have pasted my code below for reference. Kindly help.
XAML Page:
<Window x:Class="UserInterface.MainWindow"
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"
xmlns:local="clr-namespace:UserInterface"
xmlns:igDP="clr-namespace:Infragistics.Windows.DataPresenter;assembly=InfragisticsWPF.DataPresenter"
xmlns:igEditors="clr-namespace:Infragistics.Windows.Editors;assembly=InfragisticsWPF.Editors"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:dc ="clr-namespace:UserInterface.ViewModel"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
mc:Ignorable="d"
Title="MainWindow">
<Window.Resources>
<dc:GraphicViewModel x:Key="dataContext"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".5*"/>
<RowDefinition Height=".5*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".5*"/>
<ColumnDefinition Width=".5*"/>
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0" Grid.Row="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
<!--<StackPanel Orientation="Vertical" DockPanel.Dock="Top">
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="0">
<DockPanel>
<TextBlock Text="*.cfg File" Grid.Column="0" DockPanel.Dock="Left"/>
<Button Content="Browse..." Grid.Column="2" DockPanel.Dock="Right"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.cfg file..." Grid.Column="1" DockPanel.Dock="Right"/>
</DockPanel>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="1">
<TextBlock Text="*.ps File " Grid.Column="0"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.ps file..." Grid.Column="1"/>
<Button Content="Browse..." Grid.Column="2"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="2">
<TextBlock Text="*.pic File " Grid.Column="0"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.pic file..." Grid.Column="1"/>
<Button Content="Browse..." Grid.Column="2"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="3">
<TextBlock Text="*.xlsx File" Grid.Column="0"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.xlsx file..." Grid.Column="1"/>
<Button Content="Browse..." Grid.Column="2"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="4">
<TextBlock Text="*.xlsx File"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.xlsx file..." Grid.Column="1"/>
<Button Content="Browse..." Grid.Column="2"/>
</StackPanel>
</StackPanel>-->
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Margin="5" Grid.Row="0">
<TextBlock MinHeight="20.5" Text="*.cfg File" Grid.Column="0"/>
<TextBlock MinHeight="20.5" Text="*.ps File " Grid.Column="0"/>
<TextBlock MinHeight="20.5" Text="*.pic File " Grid.Column="0"/>
<TextBlock MinHeight="20.5" Text="*.xlsx File" Grid.Column="0"/>
<TextBlock MinHeight="20.5" Text="*.xlsx File" Grid.Column="0"/>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5" Grid.Row="1">
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.cfg file..." Grid.Column="1" MinHeight="20.5"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.ps file..." Grid.Column="1" MinHeight="20.5"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.pic file..." Grid.Column="1" MinHeight="20.5"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse Model mapping file..." Grid.Column="1" MinHeight="20.5"/>
<TextBox FontStyle="Italic" FontWeight="Light" Text="Browse Parameter mapping file..." Grid.Column="1" MinHeight="20.5"/>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5" Grid.Row="2">
<Button Content="Browse..." Grid.Column="2"/>
<Button Content="Browse..." Grid.Column="2"/>
<Button Content="Browse..." Grid.Column="2"/>
<Button Content="Browse..." Grid.Column="2"/>
<Button Content="Browse..." Grid.Column="2"/>
</StackPanel>
</StackPanel>
</DockPanel>
<DockPanel Grid.Column="1" Grid.Row="0">
<igDP:XamDataGrid x:Name="ItemsSource" DataContext="{Binding Source={StaticResource dataContext}, Path=ItemsSource, Mode=TwoWay}" Grid.Row="0" Margin="10" AutoFit="true">
<igDP:XamDataGrid.ViewSettings>
<igDP:GridViewSettings/>
</igDP:XamDataGrid.ViewSettings>
<igDP:XamDataGrid.FieldSettings>
<igDP:FieldSettings LabelTextAlignment="Left" AllowRecordFiltering="true" FilterOperandUIType="ExcelStyle" FilterStringComparisonType="CaseInsensitive" FilterOperatorDefaultValue="Contains"
LabelClickAction="SortByOneFieldOnlyTriState" SortComparisonType="Default"/>
</igDP:XamDataGrid.FieldSettings>
<igDP:XamDataGrid.FieldLayoutSettings>
<igDP:FieldLayoutSettings DataErrorDisplayMode="ErrorIconAndHighlight" SupportDataErrorInfo="RecordsAndCells" SelectionTypeRecord ="Single"
AutoGenerateFields="False" FilterUIType="FilterRecord"/>
</igDP:XamDataGrid.FieldLayoutSettings>
<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>
<igDP:FieldLayout.Fields>
<igDP:Field Name="IsSelected" Label="Select" HorizontalContentAlignment="Left" Width="Auto" VerticalContentAlignment="Center">
<igDP:Field.Settings>
<igDP:FieldSettings DataItemUpdateTrigger="OnCellValueChange">
<igDP:FieldSettings.LabelPresenterStyle>
<Style TargetType="{x:Type igDP:LabelPresenter}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" Content="" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</igDP:FieldSettings.LabelPresenterStyle>
</igDP:FieldSettings>
</igDP:Field.Settings>
</igDP:Field>
<igDP:Field Label="Name" Name="Name" AllowEdit="False" HorizontalContentAlignment="Left" Width="Auto">
</igDP:Field>
<igDP:Field Label="Type" Name="Type" AllowEdit="False" HorizontalContentAlignment="Left" Width="*"/>
<igDP:Field Label="Background" Name="Background" AllowEdit="False" HorizontalContentAlignment="Left" Width="Auto"/>
<igDP:Field Label="Width" Name="Width" AllowEdit="False" HorizontalContentAlignment="Right" Width="Auto"/>
<igDP:Field Label="Height" Name="Height" AllowEdit="False" HorizontalContentAlignment="Right" Width="Auto"/>
</igDP:FieldLayout.Fields>
</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>
</igDP:XamDataGrid>
</DockPanel>
<DockPanel Grid.Column="0" Grid.Row="1" Grid.RowSpan="2">
<StackPanel Orientation="Vertical" DockPanel.Dock="Bottom">
<TextBox Text="Sample Text1"/>
<TextBox Text="Sample Text2"/>
<TextBox Text="Sample Text3"/>
<TextBox Text="Sample Text4"/>
</StackPanel>
</DockPanel>
<!--</StackPanel>-->
</Grid>
</Window>
Xaml page code behind:
namespace UserInterface
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//GraphicViewModel obj = new GraphicViewModel();
//ItemsSource.DataSource = obj.ItemsSource;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion INotifyPropertyChanged Members
public GraphicViewModel GraphicViewModel
{
get { return this.DataContext as GraphicViewModel; }
set
{
this.DataContext = value;
if (this.DataContext != null)
NotifyPropertyChanged("GraphicViewModel");
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
}
}
}
Model Class:
namespace UserInterface.Model
{
public class GraphicsModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyOfPropertyChange(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected == value) return;
_isSelected = value;
NotifyOfPropertyChange("IsSelected");
}
}
private string _name = string.Empty;
public string Name
{
get { return _name; }
set
{
if (_name != value)
_name = value;
NotifyOfPropertyChange("Name");
}
}
private string _type = string.Empty;
public string Type
{
get { return _type; }
set
{
if (_type != value)
_type = value;
NotifyOfPropertyChange("Type");
}
}
private string _width = string.Empty;
public string Width
{
get { return _width; }
set
{
if (_width != value)
_width = value;
NotifyOfPropertyChange("Width");
}
}
private string _height = string.Empty;
public string Height
{
get { return _height; }
set
{
if (_height != value)
_height = value;
NotifyOfPropertyChange("Height");
}
}
}
}
ViewModel class:
namespace UserInterface.ViewModel
{
public class GraphicViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyOfPropertyChange(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
private ObservableCollection<GraphicsModel> _itemsSource = new ObservableCollection<GraphicsModel>();
// MainWindow _view = null;
public ObservableCollection<GraphicsModel> ItemsSource
{
get { return _itemsSource; }
set
{
if (_itemsSource == value) return;
_itemsSource = value;
NotifyOfPropertyChange("ItemsSource");
}
}
public GraphicViewModel()
{
//_view = view;
_itemsSource = new ObservableCollection<GraphicsModel>() { new GraphicsModel() { Name = "sdasdad", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,
new GraphicsModel() { Name = "sdsa", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,new GraphicsModel() { Name = "sdasdad", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,new GraphicsModel() { Name = "asas", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,new GraphicsModel() { Name = "rewwe", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,};
//view.GraphicViewModel = this;
}
}
}
When you write
<Window.Resources>
<dc:GraphicViewModel x:Key="dataContext"/>
</Window.Resources>
You are saying "create a property of type GraphicViewModel and name it dataContext". It's almost the exact same as doing something like this in the code-behind :
private GraphicViewModel dataContext = new GraphicViewModel();
When you write
<igDP:XamDataGrid DataContext="{Binding Source={StaticResource dataContext}, Path=ItemsSource, Mode=TwoWay}" .. />
You are saying "bind the igDP:XamDataGrid.DataContext property to dataContext.ItemsSource".
Now for why the Grid won't load, the .DataContext property doesn't actually do anything. It's just a holder for the data that sits behind the control. So if you were to write
<igDP:XamDataGrid ItemsSource="{Binding MyProperty}" />
It would be to tell WPF "set XamDataGrid.ItemsSource property equal to XamDataGrid.DataContext.MyProperty".
Since in the code above you set the DataContext equal to dataContext.ItemsSource, it would try to set the value to dataContext.ItemsSource.MyProperty (which of course does not exist).
What you actually need is something like
<igDP:XamDataGrid ItemsSource="{Binding Source={StaticResource dataContext}, Path=ItemsSource}" .. />
This binds the .ItemsSource property of the grid (which is the property it builds its data rows from) to the static resource created in <Window.Resources> named "dataContext", and the property on that object called ItemsSource.
Second issue here though is you seem to have multiple copies of your ViewModel in your code. Personally I recommend never creating objects in the XAML like you did for your GraphicViewModel. Instead, I would recommend something like this :
public MainWindow()
{
InitializeComponent();
this.DataContext = new GraphicViewModel();
}
Now it should be noted that this creates a new instance of the GraphicViewModel, but doesn't store it anywhere. If you want to access this object in other code-behind without casting this.DataContext to GraphicViewModel, then you should probably store the value somewhere.
Once the Window.DataContext is set, you can write the bindings without specifying a custom Source property for the binding.
<igDP:XamDataGrid ItemsSource="{Binding ItemsSource}" .. />
This will work because WPF controls will look up the DataContext from their parent by default if it is not specifically set. So in this case, the .DataContext property for XamDataGrid is null so it will travel up the visual tree looking for something with a DataContext until it runs into Window.DataContext which you've set in the constructor to a new instance of your GraphicViewModel.
For people looking to understand the DataContext property, I usually send them to this SO answer to avoid having to retype the same thing all the time. I'd recommend reading it if you're still working to understand what the DataContext is or how it's used.
Also that said, Dependency Injection is something different and wouldn't be used here at all.
Thanks a lot #Rachel, #Daniel Filipov & #quetzalcoatl, I got my code working now. The changes done in below files:
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
ItemsSource.DataContext= new GraphicViewModel();
}
MainWindow.xaml:
<igDP:XamDataGrid x:Name="ItemsSource" DataSource="{Binding ItemsSource, Mode=TwoWay}" .../>
I'm trying to display images in a ListView. The images are being loaded through Entity Framework from a SQL Server database. Somehow the images don't get displayed in the ListView and I can't figure out why.
I've created a test Visual Studio project.
The images are stored in an ObservableCollection<ImageViewModel>:
private ObservableCollection<ImageViewModel> images;
public ObservableCollection<ImageViewModel> Images
{
get { return images; }
set { images = value; }
}
Please let me know if you need any further details. I'm grateful for any hints that I could try out.
I'll add a screenshot as soon as I have 10 reputation.
The ImageViewModel class looks like this:
using Common;
using TestImage.Model;
namespace TestImage.ViewModel
{
class ImageViewModel : ObservableObject
{
public ImageViewModel()
{
image = new ImageTable() { Name = "unknown"};
}
#region Properties
private ImageTable image;
public ImageTable Image
{
get { return image; }
set { image = value; }
}
public string Name
{
get { return image.Name; }
set
{
if (image.Name != value)
{
image.Name = value;
RaisePropertyChanged("Name");
}
}
}
public byte[] ImageBinary
{
get { return image.ImageBinary; }
set
{
if (image.ImageBinary != value)
{
image.ImageBinary = value;
RaisePropertyChanged("ImageBinary");
}
}
}
#endregion
}
}
The MainWindow.xaml looks like this:
<Window x:Class="TestImage.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestImage.ViewModel"
Title="MainWindow" Height="375.6" Width="525">
<Window.DataContext>
<local:ImageLibrary/>
</Window.DataContext>
<Window.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="5" Margin="6">
<Image Source="{Binding Images}" Stretch="Fill" Width="100" Height="120" />
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
</Style>
</Window.Resources>
<Grid Margin="0,0,0.4,1.4">
<ListBox Name="ListBoxImages" ItemsSource="{Binding Images}" Margin="413,40,20,31.6"/>
<Image Name="ImageSource" Source="{Binding SelectedImage}" HorizontalAlignment="Left" Height="148" Margin="14,90,0,0" VerticalAlignment="Top" Width="174"/>
<Button Name="ButtonPick" Content="Pick" HorizontalAlignment="Left" Margin="14,266,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.563,-0.731" Command="{Binding CommandPickImage}"/>
<Button Name="ButtonSave" Content="Save" HorizontalAlignment="Left" Margin="113,266,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.563,-0.731" Command="{Binding CommandSaveImage}" />
<Label Name="LabelFileName" Content="FileName" HorizontalAlignment="Left" Margin="14,40,0,0" VerticalAlignment="Top" Width="60"/>
<TextBox Name="TextBoxFileName" HorizontalAlignment="Left" Height="26" TextWrapping="Wrap" VerticalAlignment="Top" Width="314" Margin="79,40,0,0" Text="{Binding SelectedFileName}"/>
<Button Name="ButtonLoad" Content="Load" HorizontalAlignment="Left" Margin="113,293,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.563,-0.731" Command="{Binding CommandLoadImage}" />
<Image Source="{Binding SelectedImageDatabase}" HorizontalAlignment="Left" Height="148" Margin="193,90,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
</Window>
The binding in the ListBox ItemTemplate should be to the ImageViewModel's ImageBinary property, instead of Images:
<DataTemplate>
<Border ...>
<Image Source="{Binding ImageBinary}" .../>
</Border>
</DataTemplate>
i,m try to learning wpf application. i try to use ninject for DI in WPF, and work perfectly. and then, i try to create login form. in this part i have some problem, i can't bind data from view to VM when the button clicked.
this my code
LoginUserControl
<UserControl x:Class="Middleware_v2._0_with_Modern_Ui.UserControls.LoginUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:vm="clr-namespace:Middleware_v2._0_with_Modern_Ui.ViewModel"
xmlns:Custom="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
mc:Ignorable="d" DataContext="{Binding Login, Source={StaticResource Locator}}">
<Border Width="400" Height="300" BorderBrush="LightBlue" CornerRadius="5" Background="SkyBlue" Margin="0,-100,0,0">
<StackPanel Margin="0,0,10,0" Width="400">
<Label VerticalAlignment="Center" HorizontalAlignment="Center"
Content="Login Form" Margin="0,30,0,0" FontSize="20" FontWeight="Bold"/>
<Label Content="User Name" Margin="84,45,197,0"/>
<TextBox Text="{Binding UserName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="150" Height="25" Margin="165,-20,85,0"/>
<Label Content="Password" Margin="84,15,197,0"/>
<PasswordBox x:Name="txt_password" Width="150" Height="25" Margin="165,-20,85,0"/>
<Button Width="100" Height="30" Margin="-110,20,0,0" Content="Login" />
<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="Click">
<GalaSoft_MvvmLight_Command:EventToCommand x:Name="btnClicked" Command="{Binding Authorize, Mode=OneTime}"/>
</Custom:EventTrigger>
</Custom:Interaction.Triggers>
<!--<Button Width="100" Height="30" Margin="110,-30,0,200" Content="Exit" />-->
</StackPanel>
<Border.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="15" Color="Gray" Direction="10"/>
</Border.Effect>
</Border>
LoginViewModel
public class LoginViewModel : ViewModelBase, ILoginViewModel
{
private readonly IAccountService _accountService;
public LoginViewModel(IAccountService _accountService)
{
this._accountService = _accountService;
Authorize = new RelayCommand(() => CheckAuthorized(), () => true);
}
public RelayCommand Authorize { get; set; }
private void CheckAuthorized()
{
User newUser = new User();
newUser.LoginName = _username;
newUser.LoginPassword = _password;
User user = _accountService.AuthenticationUser(newUser, 1);
throw new System.NotImplementedException();
}
}
LoginViewModel Interface
public interface ILoginViewModel
{
RelayCommand Authorize { get; set; }
}
how, to solve this? can some one help me
Simply
<Button Width="100" Height="30" Margin="-110,20,0,0" Content="Login" Command="{Binding Authorize}" />
I have a datagrid on a view that is bound to a viewmodel. When I initialze the view, the datagrid is populated with data from the viewmodel (ObservableCollection) as it should. However, with I try to do a search against the data, the datagrid does not get refreshed from the viewmodel. When I breakpoint the code in my viewmodel, I can see the results in the ObservableCollection has changed per my search, but somehow that is not getting communicated back to the view. Here is my view and viewmodel (BTW, I am using VS2010 RTM):
namespace Attendance.ViewModels
{
public class EmployeeSelectViewModel : ViewModel, INotifyPropertyChanged
{
#region Entity list and constructor
public EmployeeSelectViewModel()
{
{
Initialize();
}
}
private void Initialize()
{
if (employeeRpository == null)
employeeRpository = new EmployeeRepository();
ListOfEmployees = new ObservableCollection<EmployeeDto>(employeeRpository.GetEmployees(true));
}
private EmployeeRepository employeeRpository;
private ObservableCollection<EmployeeDto> listOfEmployees;
public ObservableCollection<EmployeeDto> ListOfEmployees
{
get { return listOfEmployees; }
set
{
if (listOfEmployees != value)
{
listOfEmployees = value;
NotifyPropertyChanged("ListOfEmployee");
}
}
}
private EmployeeDto selectedEmployee;
public EmployeeDto SelectedEmployee
{
get { return selectedEmployee; }
set
{
if (selectedEmployee != value)
{
selectedEmployee = value;
NotifyPropertyChanged("SelectedEmployee");
}
}
}
#endregion
#region UI control references
/// <summary>
/// search text property
/// </summary>
private string searchText;
public string SearchText
{
get { return searchText; }
set
{
if (searchText != value)
{
searchText = value;
NotifyPropertyChanged("SearchText");
}
}
}
public string Location { get; set; }
#endregion
#region Relay Commands
/// <summary>
/// new command
/// </summary>
private ViewCommand newCommand;
public ViewCommand NewCommand
{
get
{
if (newCommand == null)
newCommand = new ViewCommand(param => this.NewEmployee());
return newCommand;
}
}
private void NewEmployee()
{
NavigationActions.NewEmployeeView();
}
/// <summary>
/// edit command
/// </summary>
private ViewCommand editCommand;
public ViewCommand EditCommand
{
get
{
if (editCommand == null)
{
editCommand = new ViewCommand(param => this.EditEmployee());
}
return editCommand;
}
}
private void EditEmployee()
{
NavigationActions.OpenEmployeeView(SelectedEmployee);
}
/// <summary>
/// save command
/// </summary>
private ViewCommand saveCommand;
public ViewCommand SaveCommand
{
get
{
if (saveCommand == null)
{
saveCommand = new ViewCommand(
param => this.SaveEmployee(),
param => this.CanSaveEmployee
);
}
return saveCommand;
}
}
public void SaveEmployee()
{
employeeRpository.SaveChanges();
}
private bool CanSaveEmployee
{
get { return true; }
}
/// <summary>
/// clear search command
/// </summary>
private ViewCommand clearSearchCommand;
public ViewCommand ClearSearchCommand
{
get
{
if (clearSearchCommand == null)
clearSearchCommand = new ViewCommand(param => this.ClearSearch());
return clearSearchCommand;
}
}
private void ClearSearch()
{
this.SearchText = string.Empty;
ListOfEmployees = new ObservableCollection<EmployeeDto>(employeeRpository.GetEmployees(true));
}
/// <summary>
/// search command
/// </summary>
private ViewCommand searchCommand;
public ViewCommand SearchCommand
{
get
{
if (searchCommand == null)
searchCommand = new ViewCommand(param => this.SearchEmployee());
return searchCommand;
}
}
private void SearchEmployee()
{
if (this.SearchText == string.Empty || this.SearchText == null)
{
NavigationActions.ShowError("Search Employees.", "Please enter your search text ...");
return;
}
ListOfEmployees = new ObservableCollection<EmployeeDto>(employeeRpository.GetEmployeesByQuery(SearchText, Location));
}
/// <summary>
/// exit command
/// </summary>
private ViewCommand exitCommand;
public ViewCommand ExitCommand
{
get
{
if (exitCommand == null)
{
exitCommand = new ViewCommand(param => this.ExitWindow());
}
return exitCommand;
}
}
private void ExitWindow()
{
NavigationActions.CloseCurrentView();
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
}
<Window x:Class="Attendance.Views.EmployeeSelectView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Attendance.ViewModels"
Title="Employee Maintenance" FocusManager.FocusedElement="{Binding ElementName=txtSearchCriteria}"
Height="525" Width="800" WindowStartupLocation="CenterScreen" WindowState="Normal"
WindowStyle="SingleBorderWindow" Icon="Images/gb_icon.png">
<Window.DataContext>
<vm:EmployeeSelectViewModel />
</Window.DataContext>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/DataGrid.Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
<!--xml data start-->
<XmlDataProvider x:Key="LocationData" XPath="LocationList/LocationItem" Source="XMLData/Location.xml"/>
<!--xml data end-->
</ResourceDictionary>
</Window.Resources>
<Grid Width="775">
<DockPanel HorizontalAlignment="Left" Width="770">
<!-- TOOLBAR -->
<DockPanel DockPanel.Dock="Top" MinHeight="30" Margin="5">
<ToolBar FontWeight="Bold">
<!-- NEW -->
<Button Name="btnNew" Command="{Binding Path=NewCommand}">
<Button.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="SteelBlue" Foreground="White">
Create a new Customer
</Label>
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
Create a new customer in a new Window tab.
</TextBlock>
<Line Stroke="SteelBlue" StrokeThickness="1" X2="200" />
<StackPanel Orientation="Horizontal">
<Image Margin="2" Source="Images/new.png"/>
<Label>Press F1 for more help</Label>
</StackPanel>
</StackPanel>
</Button.ToolTip>
<StackPanel Orientation="Horizontal">
<Image Source="Images/new.png" Width="22" Height="22" Margin="2"/>
<Label VerticalAlignment="Center">_New</Label>
</StackPanel>
</Button>
<!-- EDIT -->
<Button Name="btnEdit" Command="{Binding Path=EditCommand}">
<Button.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="SteelBlue" Foreground="White">
Edit the current record
</Label>
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
Edit the current selected Customer.
</TextBlock>
<Line Stroke="SteelBlue" StrokeThickness="1" X2="200" />
<StackPanel Orientation="Horizontal">
<Image Margin="2" Source="Images/dialog-information.png"/>
<Label>Press F1 for more help</Label>
</StackPanel>
</StackPanel>
</Button.ToolTip>
<StackPanel Orientation="Horizontal">
<Image Source="Images/edit.png" Width="22" Height="22" Margin="2" />
<Label VerticalAlignment="Center">_Edit</Label>
</StackPanel>
</Button>
<!-- SEARCH -->
<Separator />
<TextBox Name="txtSearchCriteria"
MinWidth="300" Margin="5"
BorderThickness="1" BorderBrush="LightGray"
FontWeight="Normal" Foreground="Gray" Text="{Binding Path=SearchText}">
</TextBox>
<Button Name="btnSearch" Command="{Binding Path=SearchCommand}">
<Button.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="SteelBlue" Foreground="White">
Search
</Label>
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
Search a specific Customer.
</TextBlock>
<Line Stroke="SteelBlue" StrokeThickness="1" X2="200" />
<StackPanel Orientation="Horizontal">
<Image Margin="2" Source="Images/find.png"/>
<Label>Press F1 for more help</Label>
</StackPanel>
</StackPanel>
</Button.ToolTip>
<StackPanel Orientation="Horizontal">
<Image Source="Images/find.png" Width="22" Height="22" Margin="2" />
<Label VerticalAlignment="Center">_Find</Label>
</StackPanel>
</Button>
<Button Name="btnClearSearch" Command="{Binding Path=ClearSearchCommand}">
<Button.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="SteelBlue" Foreground="White">
Search
</Label>
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
Clear search results.
</TextBlock>
<Line Stroke="SteelBlue" StrokeThickness="1" X2="200" />
<StackPanel Orientation="Horizontal">
<Image Margin="2" Source="Images/find.png"/>
<Label>Press F1 for more help</Label>
</StackPanel>
</StackPanel>
</Button.ToolTip>
<StackPanel Orientation="Horizontal">
<Label VerticalAlignment="Center">_Clear Search</Label>
</StackPanel>
</Button>
<!-- EXIT -->
<Separator />
<Button Name="btnExit" Command="{Binding Path=ExitCommand}">
<Button.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="SteelBlue" Foreground="White">
Start the application
</Label>
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
Start the main application with the M-V-MV pattern.
</TextBlock>
<Line Stroke="SteelBlue" StrokeThickness="1" X2="200" />
<StackPanel Orientation="Horizontal">
<Image Margin="2" Source="Images/dialog-information.png"/>
<Label>Press F1 for more help</Label>
</StackPanel>
</StackPanel>
</Button.ToolTip>
<StackPanel Orientation="Horizontal">
<Image Source="Images/exit.png" Width="22" Height="22" Margin="2" />
<Label VerticalAlignment="Center">_Exit</Label>
</StackPanel>
</Button>
</ToolBar>
</DockPanel>
<!-- LIST -->
<DockPanel DockPanel.Dock="Top" MinHeight="30" Margin="0,0,0,5">
<Label>Location:</Label>
<ComboBox Name="cboLocation" Grid.Column="1" Grid.Row="4"
ItemsSource="{Binding Source={StaticResource LocationData}}"
DisplayMemberPath="location_text" SelectedValuePath="location_value"
SelectedValue="{Binding Path=Location}"
HorizontalAlignment="Left" Width="175" Margin="4" />
</DockPanel>
<DockPanel Margin="5">
<DataGrid ItemsSource="{Binding Path=ListOfEmployees}" AutoGenerateColumns="False" IsReadOnly="True"
Name="dgEmployee" SelectionMode="Single" SelectionUnit="FullRow" CanUserResizeColumns="True"
SelectedItem="{Binding Path=SelectedEmployee}" GridLinesVisibility="Horizontal">
<DataGrid.Columns>
<DataGridTextColumn Header="Employee ID" Width="SizeToCells" MinWidth="125" Binding="{Binding EmployeeID}" />
<DataGridTextColumn Header="First Name" Width="SizeToCells" MinWidth="200" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="Last Name" Width="SizeToCells" MinWidth="200" Binding="{Binding LastName}" />
<DataGridTextColumn Header="Location" Width="SizeToCells" MinWidth="125" Binding="{Binding Location}" />
<DataGridCheckBoxColumn x:Name="Active" Header="Active" Binding="{Binding active}" MinWidth="75" />
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</DockPanel>
</Grid>
This was my solution:
<DataGrid Name="dgrid" ItemsSource="{Binding UserSettings, IsAsync=True}" AutoGenerateColumns="False">
The key being the setting of IsAsync=True, allows the screen paint to occur
I found 2 ways to refresh DataGrid:
One was posted by VariableLost, it works with INotifyPropertyChanged but have one drawback. Whole DataGrid is refreshed with blink effect (disappears for a split second). Doesn't look natural.
Other solution is to refresh ObservableCollection in ViewModel or Code Behind (if you're not using MVVM):
CollectionViewSource.GetDefaultView(collectionName).Refresh();
Looks more natural because only changes cells affected by edition.
Your previous code should have also worked, but 'magic strings' got in the way.
Property name is ListOfEmployees and in its setter you raise PropertyChanged event with property name ListOfEmployee. 's' is missing.
Beware of your new code. It will raise CollectionChanged event on ListOfEmployees for every insertion, and that might make your app slower if you are doing many insertions.
For many insertions, it would be better to derive from ObservableCollection and implement Reset method that clears underlying Items, adds new items and raises CollectionChanged event of type Reset.
My question was answered in a post on another site. Instead of creating a new instance of the ListOfEmployees in my view model, I just cleared the existing one and added the results from my repository:
private void SearchEmployee()
{
if (String.IsNullOrEmpty(this.SearchText) || String.IsNullOrEmpty(this.Location))
{
NavigationActions.ShowError("Search Employees.", "Please enter your search text and select a location...");
return;
}
// clear the list and repopulate based on the search criteria
if (ListOfEmployees != null)
{
ListOfEmployees.Clear();
IList<EmployeeDto> iList = employeeRpository.GetEmployeesByQuery(SearchText, Location, IsActive);
foreach (EmployeeDto value in iList)
ListOfEmployees.Add(value);
}
}
That did the trick.