wpf autocompletebox binding - c#

I've created some UserControls which are wrapping some standard controls, for example: a textbox/combobox + Image + textblock. I'm trying to do the same thing with AutoCompleteBox and have failed so far...
The list of items is shown fine, I can select na item, but that doesn't trigger a change to the SelectedItem. I'm using almost the same code for combobox so not sure what's wrong...
Anyway I've played around with ValueMemberPath / ValueMemberBinding on the AutoCompleteBox but not sure if that's the way to go.
The UserControl xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Margin="0,0,2,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding ElementName=ACProperty, Path=ImageSource}" VerticalAlignment="Center"
MaxHeight="30" MaxWidth="30" Margin="1" Grid.Column="0" RenderOptions.BitmapScalingMode="HighQuality"/>
<TextBlock Text="{Binding ElementName=ACProperty, Path=Label}" VerticalAlignment="Center"
HorizontalAlignment="Left" Grid.Column="1" Margin="1" TextWrapping="Wrap" Width="100" />
</Grid>
<toolkitInput:AutoCompleteBox FilterMode="ContainsOrdinal" IsTextCompletionEnabled="True"
ItemsSource="{Binding ElementName=ACProperty, Path=ItemsSource}"
SelectedItem="{Binding ElementName=ACProperty, Path=SelectedItem}"
MinimumPrefixLength="2"
MinimumPopulateDelay="300"
VerticalAlignment="Center"
HorizontalAlignment="Stretch" Grid.Column="1" Margin="1,1,2,1" />
</Grid>
The code behind:
public static DependencyProperty LabelProperty = DependencyProperty.Register(
"Label", typeof(string), typeof(AutoCompleteProperty));
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(object), typeof(AutoCompleteProperty));
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(AutoCompleteProperty),
new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
public static DependencyProperty ImageSourceProperty = DependencyProperty.Register(
"ImageSource", typeof(string), typeof(AutoCompleteProperty));
public object ItemsSource
{
get
{
return (object)GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
}
}
public object SelectedItem
{
get
{
return (object)GetValue(SelectedItemProperty);
}
set
{
SetValue(SelectedItemProperty, value);
}
}
public string Label
{
get
{
return (string)GetValue(LabelProperty);
}
set
{
SetValue(LabelProperty, value);
}
}
public string ImageSource
{
get
{
return (string)GetValue(ImageSourceProperty);
}
set
{
SetValue(ImageSourceProperty, value);
}
}
And in a UserControl/Window where I would like to use it:
<cont:AutoCompleteProperty Label="Product Category"
ItemsSource="{Binding Path=ProductCategories}"
SelectedItem="{Binding Path=ProductCategory}"
ImageSource="..."/>

I have updated binding in the following code....
<UserControl x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350" Width="525"
xmlns:toolkitInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
x:Name="root"
>
<Grid>![enter image description here][1]
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Margin="0,0,2,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding ImageSource,ElementName=root}" VerticalAlignment="Center" MaxWidth="100" Margin="1" Grid.Column="0" RenderOptions.BitmapScalingMode="HighQuality"/>
<TextBlock Text="{Binding Label,ElementName=root}" DataContext="{Binding RelativeSource={RelativeSource Self}}" VerticalAlignment="Center"
HorizontalAlignment="Left" Grid.Column="1" Margin="1" TextWrapping="Wrap" Width="100" />
</Grid>
<toolkitInput:AutoCompleteBox FilterMode="ContainsOrdinal" IsTextCompletionEnabled="True"
ItemsSource="{Binding ItemsSource,ElementName=root}"
SelectedItem="{Binding SelectedItem,ElementName=root}"
MinimumPrefixLength="2"
MinimumPopulateDelay="300"
VerticalAlignment="Center"
HorizontalAlignment="Stretch" Grid.Column="1" Margin="1,1,2,1" />
</Grid>
</UserControl>
Here is a image of the window using the above code

I made few changes in your bindings.
Observe usercontrol DataContext.
<UserControl x:Class="WpfApplication1.AutoCompleteProperty"
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"
mc:Ignorable="d"
xmlns:toolkitInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
d:DesignHeight="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Margin="0,0,2,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding ImageSource}" VerticalAlignment="Center" MaxWidth="100" Margin="1" Grid.Column="0" RenderOptions.BitmapScalingMode="HighQuality"/>
<TextBlock Text="{Binding Label}" VerticalAlignment="Center"
HorizontalAlignment="Left" Grid.Column="1" Margin="1" TextWrapping="Wrap" Width="100" />
</Grid>
<toolkitInput:AutoCompleteBox FilterMode="ContainsOrdinal" IsTextCompletionEnabled="True"
ItemsSource="{Binding ItemsSource}"
SelectedItem="{Binding SelectedItem}"
MinimumPrefixLength="2"
MinimumPopulateDelay="300"
VerticalAlignment="Center"
HorizontalAlignment="Stretch" Grid.Column="1" Margin="1,1,2,1" />
</Grid>
</UserControl>
and no changes in code behind file

Related

How to set Listview Itemtemplate when drag drop in wpf

I have create simple drag drop in WPF. In my application there are two Listviews. I have to drag list items from first listview and drop the item to second listview. I have created custom data template for first listview. When i drag the first listview item into second listview the data template is not customized so items are not displayed. How to display the list items with generic. Please help. My Code is as below,
<Grid Margin="0,20,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ListBox
Name="memberCollection"
Grid.Column="1"
Width="150"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
PreviewMouseLeftButtonDown="memberCollection_PreviewMouseLeftButtonDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBox Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid
Name="gridDrop"
Grid.Column="0"
Margin="20,0,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ListBox.Drop="grid_Drop"
ShowGridLines="True">
<ListBox
Grid.Row="0"
Grid.Column="0"
Margin="10,10,0,0"
AllowDrop="True" />
</Grid>
</Grid>
Code Behind
ObservableCollection<Member> member = new ObservableCollection<Member>();
public MainWindow()
{
InitializeComponent();
member.Add(new Member { Name = "Karthick", ID = "20011", Address = "10, MainRoad, Chennai" });
memberCollection.ItemsSource = member;
DataContext = new Member();
}
private void memberCollection_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
object selectedMember = memberCollection.SelectedItem as Member;
if (selectedMember != null)
DragDrop.DoDragDrop(memberCollection, selectedMember, DragDropEffects.All);
}
private void grid_Drop(object sender, RoutedEventArgs e)
{
ListBox listContent = e.Source as ListBox;
if (listContent != null)
Console.WriteLine("", Grid.GetColumn(listContent), Grid.GetRow(listContent));
DataObject item = (((DragEventArgs)e).Data) as DataObject;
object Target = ((Grid)(sender)).DataContext;
object listItem = item.GetData(Target.GetType());
if (listItem != null)
{
//listContent.Items.Add(listItem.Name.ToString());
//listContent.Items.Add(listItem.ID.ToString());
//listContent.Items.Add(listItem.Address.ToString());
//listContent.ItemTemplate = memberCollection.ItemTemplate;
listContent.Items.Add(listItem);
}
}
If you define the DataTemplate as a reusable resource, you can use it in both ListBoxes:
<Grid Margin="0,20,0,0">
<Grid.Resources>
<DataTemplate x:Key="dataTemplate">
<StackPanel>
<TextBox Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ListBox
Name="memberCollection"
Grid.Column="1"
Width="150"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
PreviewMouseLeftButtonDown="memberCollection_PreviewMouseLeftButtonDown"
ItemTemplate="{StaticResource dataTemplate}" />
<Grid
Name="gridDrop"
Grid.Column="0"
Margin="20,0,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ListBox.Drop="grid_Drop"
ShowGridLines="True">
<ListBox
Grid.Row="0"
Grid.Column="0"
Margin="10,10,0,0"
AllowDrop="True"
ItemTemplate="{StaticResource dataTemplate}"/>
</Grid>
</Grid>
If you want to display some other properties of the dropped Member in the second ListBox, you should define another ItemTemplate:
<ListBox
Grid.Row="0"
Grid.Column="0"
Margin="10,10,0,0"
AllowDrop="True">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Id}" />
<TextBlock Tag="{Binding Address}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Bind Combobox in WPF to Entity class

I have a data input form where i have textboxes,comboboxes and datepickers. I want to Bind comboboxes to the DB column so that users select the correct value for insertion. I have attached the viewmodel class and XAML code. In the viewmodel code "private void GetSW()" - this gets all the list of the entity class and "private void addSW()" this adds the record to the DB, Except the combobox binding everything works fine. in XAML i have binded combobox like this but this give blank combobox, please help what i am missing. I researched many topics on this forum but didn't find any solution
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding newSW.PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
Its a ViewModel Code
using BusinessEntities;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MUDB.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MUDB.Ui.Logic
{
public class SoftwareVersionListViewModel:ViewModelBase
{
private bool enableRowDetails=false;
public bool EnagleRowDetails
{
get { return enableRowDetails; }
set {
enableRowDetails = value;
RaisePropertyChanged();
}
}
public SoftwareVersionListViewModel()
{
SaveSW = new RelayCommand(addSW);
//savecommand = new RelayCommand(addprod);
GetSW();
newSW = new SoftwareDefEntity();
EditSW = new RelayCommand(() => {
EnagleRowDetails = true;
MessageBox.Show("Edit button clicked!!");});
//SWList = new SoftwareDefEntity(); //Initializing the object of the Entity class
}
public List<SoftwareDefEntity> SWentities
{
get;
set;
}
private SoftwareDefEntity _selectedsw;
public SoftwareDefEntity Selectedsw
{
get { return _selectedsw; }
set
{
_selectedsw = value; //This will get all the values of that particular Selected row that are defined in the entity class
EnagleRowDetails = false; //Reset boolean value EnagleRowDetails, so that the selected rowdetails are disabled until Edit button is not clicked.
//ShowView();
}
}
public RelayCommand SaveSW { get; private set; }
public RelayCommand EditSW { get; private set; }
public SoftwareDefEntity newSW { get; private set; }
private void ShowView()
{
//cUSTOM METHODS
}
private void GetSW() // Method that reads the data from the service layer
{
SWDefService obj = new SWDefService();
SWentities = obj.getSW() ; //getSW is the method refered in Service layer
}
private void addSW()
{
SWDefService obj = new SWDefService();
obj.addSW(newSW); //newproduct object will hold the value of the binded control, in XAML its binded like this "{Binding newproduct.ProductName(ProductName is the field name in the entityclass/DB table)}"
newSW = new SoftwareDefEntity();
}
}
}
This is the XAML Code
<UserControl x:Class="MUDB.Ui.CreateSW"
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:local="clr-namespace:MUDB.Ui"
xmlns:converter="clr-namespace:MUDB.Ui.Logic.Converters;assembly=MUDB.Ui.Logic"
xmlns:enums="clr-namespace:MUDB.Ui.Logic.Enums;assembly=MUDB.Ui.Logic"
mc:Ignorable="d" Height="Auto" Width="Auto"
DataContext="{Binding SoftwareVersionList,Source={StaticResource Locator}}" >
<UserControl.Resources>
<converter:RadioButtonToBooleanConverter x:Key="RadioButtonToBooleanConverter" />
</UserControl.Resources>
<Grid>
<Border Background="#90000000" Visibility="{Binding Visibility}">
<Border BorderBrush="Black" BorderThickness="1" Background="White"
CornerRadius="10,0,10,0" VerticalAlignment="Center"
HorizontalAlignment="Center">
<Border.BitmapEffect>
<DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" />
</Border.BitmapEffect>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="100"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Label Content="Create New Software Version" Grid.Column="0" Grid.Row="0" Foreground="White" Background="black"
HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.ColumnSpan="3" />
<Label Content="ECU" Grid.Column="0" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Software Name" Grid.Column="1" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Previous Software" Grid.Column="2" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Request Freeze Date" Grid.Column="0" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Request Freeze Status" Grid.Column="1" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Software Freeze Date" Grid.Column="0" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<Label Content="Software Freeze Status" Grid.Column="1" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<Label Content="Comments" Grid.Column="0" Grid.Row="7" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<ComboBox x:Name="ECU" Grid.Column="0" Grid.Row="2" Text="{Binding newSW.ECU}" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80" Height="Auto">
<ComboBoxItem Name="cbi1">ACM</ComboBoxItem>
<ComboBoxItem Name="cbi2">MCM</ComboBoxItem>
</ComboBox>
<TextBox x:Name="SW" Grid.Column="1" Grid.Row="2" Text="{Binding newSW.SoftwareName}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="150" />
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
<DatePicker Grid.Column="0" Grid.Row="4" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.Req_Freeze_Date}" Height="Auto" Width="Auto"/>
<DatePicker Grid.Column="0" Grid.Row="6" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.SW_Freeze_Date}" Height="Auto" Width="Auto"/>
<RadioButton Content="Yes" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" HorizontalAlignment="Left" VerticalAlignment="Top" Height="14" Width="Auto"/>
<RadioButton Content="No" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" Margin="60 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<RadioButton Content="Yes" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<RadioButton Content="No" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" Margin="60 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<TextBox x:Name="CommenttextBox" Grid.Column="1" Grid.Row="7" HorizontalAlignment="Left" Height="69" TextWrapping="WrapWithOverflow" VerticalAlignment="Center" Text="{Binding Comment}" Width="170" Margin="4.4,2.2,0,0" />
<UniformGrid Grid.Row="9" Margin="2" Columns="2" HorizontalAlignment="Stretch"
VerticalAlignment="Center" Height="Auto">
<Button x:Name="SaveButton" Command="{Binding SaveSW}" Content="Save" Height="27" />
<Button x:Name="CloseButton" Click="CloseButton_Click" Content="Close" Height="26" />
</UniformGrid>
</Grid>
</Border>
</Border>
</Grid>
</UserControl>
I guess you want to display the list of SoftwareDefEntity objects in your ComboBox.
Bind to the SWentities property then:
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding SWentities}" DisplayMemberPath="Name" ... />
And raise the PropertyChanged event in its setter of this property:
private List<SoftwareDefEntity> _swEntities;
public List<SoftwareDefEntity> SWentities
{
get { return _swEntities; }
set { _swEntities = value; RaisePropertyChanged(); }
}
This is the code to bind the data to combobox. i did not add any of other controls since those are working fine at your place. Observable collection is easy way to bind combobox .
Here is your View Model..
public class SoftwareVersionListViewModel : ViewModelBase
{
public SoftwareVersionListViewModel()
{
GetSW();
}
//Define the observable collection
private ObservableCollection<SoftwareDefEntity> _SWmappings2 = new ObservableCollection<SoftwareDefEntity>();
//here is your Entity list
public List<SoftwareDefEntity> SWentities
{
get;
set;
}
// Obeservable collection property for access
public ObservableCollection<SoftwareDefEntity> SWmappings2
{
get { return _SWmappings2; }
set
{
_SWmappings2 = value;
OnPropertyChanged("appeventmappings2");
}
}
/// <summary>
/// load the combobox
/// </summary>
private void GetSW() // Method that reads the data from the service layer
{
SWDefService obj = new SWDefService();
SWentities = obj.getSW(); //getSW is the method refered in Service layer
SWentities.ForEach(_SWmappings2.Add);
}
}
and Xaml...
<ComboBox x:Name="ComboBox" ItemsSource="{Binding SWmappings2, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="PreviousSW" SelectedItem="{Binding PreviousSW, Mode=TwoWay}" Grid.Row="0" >
</ComboBox>

Change Background color of grid row when selected

My itemscontrol is currently loading each row correctly. I am trying to get it to change the background color of each row when the user selects it.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0">
<Border BorderBrush="#BBBDBF" Background="#F4F4F4" BorderThickness="0,1,0,1" Margin="10,10,10,10"/>
<Image HorizontalAlignment="Left" Margin="10,0,0,0" Height="38" Width="38" Source="C:\Users\linda_l\Pictures\Cloud upload\database (1).png" />
<TextBlock FontSize="50" Foreground="#4092C2" Margin="60,0,0,0" HorizontalAlignment="left" Height="69" >Databases</TextBlock>
</Grid>
<Grid Background="White" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Border BorderBrush="#BBBDBF" BorderThickness="0,0,0,1" Grid.Column="1" />
<Label Grid.Column="1" Content="Server Name" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
<Border BorderBrush="#BBBDBF" BorderThickness="1,0,0,1" Grid.Column="2" />
<Label Grid.Column="2" Content="Source Database" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
<Border BorderBrush="#BBBDBF" BorderThickness="1,0,0,1" Grid.Column="3" />
<Label Grid.Column="3" Content="Destination Database" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
<Border BorderBrush="#BBBDBF" BorderThickness="1,0,0,1" Grid.Column="4" />
<Label Grid.Column="4" Content="Status" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
</Grid>
<ItemsControl x:Name="itemscntrl" ItemsSource="{Binding DatabaseServers}" Background="White" BorderBrush="WhiteSmoke" BorderThickness="0" Grid.Row="2" Margin="0,5,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="grd" Background="White" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Image Source="{Binding StatusImage}" Height="10" Width="10" />
<Label Grid.Column="1" HorizontalAlignment="Left" Content="{Binding ServerName}" />
<Label Grid.Column="2" HorizontalAlignment="Left" Content="{Binding SourceDatabase}" />
<TextBox x:Name="dst" Grid.Column="3" Text="{Binding DestinationDatabase , Mode=TwoWay, UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top" />
<Label Grid.Column="4" Content="{Binding Status}" VerticalAlignment="Top" />
<Button Grid.Column="4" BorderThickness="0" HorizontalAlignment="Center" Width="50" Margin="3" Content="{Binding Status}" Command="{Binding EnabledCommand}" CommandParameter="{Binding}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding selected }" Value="True">
<Setter Property="Background" Value="Yellow" TargetName="dst" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Which currently looks like this:
I tried adding a DataTemplate.Triggers but it doesn't seam to do anything. How exactly do you detect that a row in a itemscontrol has been selected? The only examples I have found use a datagrid. I tried changing mine to a datagrid instead of the itemscontrol, but then the it wouldn't load the data.
Datagrid:
<DataGrid x:Name="grd" Background="White" DataContext="{Binding DatabaseServers}" Grid.Row="2">
<Image Source="{Binding StatusImage}" Height="10" Width="10" />
<Label Grid.Column="1" HorizontalAlignment="Left" Content="{Binding ServerName}" />
<Label Grid.Column="2" HorizontalAlignment="Left" Content="{Binding SourceDatabase}" />
<TextBox x:Name="dst" Grid.Column="3" Text="{Binding DestinationDatabase , Mode=TwoWay, UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top" />
<Label Grid.Column="4" Content="{Binding Status}" VerticalAlignment="Top" />
<Button Grid.Column="4" BorderThickness="0" HorizontalAlignment="Center" Width="50" Margin="3" Content="{Binding Status}" Command="{Binding EnabledCommand}" CommandParameter="{Binding}" />
</DataGrid>
Just shows a bunch of lines there is no data in each row.
I am very new to WPF so I cant really figure out what I am doing wrong here.
Here is what you want using DataGrid i m using MVVM
Window.xaml
<Grid Margin="10">
<StackPanel Orientation="Vertical">
<Label Content="DataBases" Width="150" Height="50" HorizontalAlignment="Left" FontSize="20"/>
<DataGrid Name="DgDataSource" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding SourceData}">
<DataGrid.Columns>
<DataGridTextColumn Header="ServerName" Binding="{Binding ServerName}" Width="2*"/>
<DataGridTextColumn Header="SourceDatabase" Binding="{Binding SourceDatabase}" Width="2*"/>
<DataGridTextColumn Header="DestinationDatabase" Binding="{Binding DestinationDatabase}" Width="2*"/>
<DataGridTemplateColumn Width="*" Header="Status" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Status}" Command="{Binding EnabledCommand}"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
View Model
public class WindowViewModel
{
public ObservableCollection<DataSource> SourceData { get; set; }
public WindowViewModel()
{
Initialize();
}
private void Initialize()
{
SourceData = new ObservableCollection<DataSource>
{
new DataSource() {Status = "Stop", ServerName = "Test 1", SourceDatabase = "Unknown",DestinationDatabase = "blabla....."},
new DataSource() {Status = "Work", ServerName = "Test 2", SourceDatabase = "Unknown",DestinationDatabase = "blabla....."},
new DataSource() {Status = "Stop", ServerName = "Test 3", SourceDatabase = "Unknown",DestinationDatabase = "blabla....."}
};
}
}
Model
public class DataSource
{
public string Status { get; set; }
public string ServerName { get; set; }
public string SourceDatabase { get; set; }
public string DestinationDatabase { get; set; }
}

How to bind dictionary key with the listbox textblock?

I've got a problem get binding working in an DataTemplate of a ListView. My binding target is a KeyValuePair.
this is MY XAML Code:-
<ListBox x:Name="ListBox_Setting" ItemsSource="{Binding DictTemperature}" BorderBrush="Black" BorderThickness="1" Height="582" Width="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="78">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="Img_ListSetting" Width="50" Height="50" Source="/Assets/un-checked.png" Margin="18,7,507,21" />
<TextBlock x:Name="Tb_ListSetting" Text="{Binding Path=Key}" FontFamily="OpenSans" FontSize="30" Margin="89,0,18,20" Height="42" VerticalAlignment="Bottom" />
<Rectangle x:Name="Line_ListSetting" Height="1" Margin="15,66,15,11" Fill="#FF3498DB"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And This is My C# Code :-
public Dictionary<string, bool> DictTemperature { set; get; }
DictTemperature = new Dictionary<string, bool>();
if (!appSettings.Contains("AppTemperature"))
{
DictTemperature.Add("Celsius", true);
DictTemperature.Add("Fahrenheit", true);
DictTemperature.Add("Kelvin", true);
DictTemperature.Add("Rankine", true);
appSettings.Add("AppTemperature", DictTemperature);
}
DictTemperature = (Dictionary<string, bool>)appSettings["AppTemperature"];
here listbox is showing count as 4 and showing the key value pairs also but unable to bind key with the textblock.
Please tell me the solution....
You can do it Shown here (Binding a Dictionary's key and value in a listbox with wpf)

Binding StringFormat giving incorrect result

For some reason using Content="{Binding Time, StringFormat=t} is still giving me a long date. The backing field is a DateTime property initialised with DateTime.Now but no matter what string format I try it still shows the full date...
I would like only to see HH:mm tt
Any ideas?
XAML :
<Window x:Class="ArgosSystem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ArgosSystem"
xmlns:sys="clr-namespace:System;assembly=System"
Title="MainWindow" Height="800" Width="1280" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:Picknote}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" MinWidth="200" />
<ColumnDefinition Width="350" />
<ColumnDefinition Width="250" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Label Content="{Binding Time, StringFormat=t}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="0" />
<Label Content="{Binding Customer}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="1" />
<Label Content="{Binding PicknoteNo}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="2" />
<Label Content="{Binding Qty}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="3" />
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Background="Black">
<DockPanel>
<ScrollViewer Name="lstPicknoteScroll" VerticalScrollBarVisibility="Auto">
<ItemsControl Name="lstPicknotes" ItemsSource="{Binding}" IsTabStop="False" Foreground="Cornsilk" />
</ScrollViewer>
</DockPanel>
</Grid>
</Window>
C# :
public partial class MainWindow : Window
{
ObservableCollection<Picknote> picknotes = new ObservableCollection<Picknote>();
public MainWindow()
{
InitializeComponent();
lstPicknotes.DataContext = picknotes;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
picknotes.Add(new Picknote
{
Time = DateTime.Now,
Customer = "REED FOR SPEED",
PicknoteNo = "PKN767677",
Qty = 100
});
picknotes.Add(new Picknote
{
Time = DateTime.Now.AddHours(-2),
Customer = "F1 AUTOMOTIVE",
PicknoteNo = "PKN767677",
Qty = 50
});
picknotes.Add(new Picknote
{
Time = DateTime.Now.AddHours(-1),
Customer = "FERGUSENS",
PicknoteNo = "PKN767677",
Qty = 10
});
}
}
StringFormat works on properties of type string. The Content property is of type Object so you need to specify the format using ContentStringFormat property of Label control.
<Label Content="{Binding Time}" ContentStringFormat="t" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="0" />

Categories