DataBind to Combobox In SilverLight 4 .0 - silverlight-4.0

I am trying to databind to the combobox. Data is coming from a database table which name is tbltest and table has 2 fileds id and name.
When I am trying to bind name to combox it display me tbltest:name in View. I am using domain services and MVVM to bind data.
Below is my code of ViewModel:
public ViewModel()
{
var query = context.GetTblTestsQuery();
var load = context.Load(query);
load.Completed += (s, ea) =>
{
ObsCompanyCollection = new ObservableCollection<tblTest>(context.tblTests);
};
}
private ObservableCollection<tblTest> _ObsCompanyCollection = new ObservableCollection<tblTest>();
public ObservableCollection<tblTest> ObsCompanyCollection
{
get
{
return _ObsCompanyCollection;
}
set
{
if (_ObsCompanyCollection != value)
{
_ObsCompanyCollection = value;
NotifyPropertyChanged("ObsCompanyCollection");
}
}
}
and Below is code of my XAml file:
<UserControl.Resources>
<my:ViewModel x:Key="ViewModel"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}">
<ComboBox Height="23" HorizontalAlignment="Left" Margin="47,128,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" DisplayMemberPath="{Binding name,Mode=TwoWay}" ItemsSource="{Binding ObsCompanyCollection,Mode=TwoWay}" SelectedItem="{Binding tbldata.SelectCompanyId,Mode=TwoWay}" />
I dont know what is wrong with this code. I want only name to display in my combobox.
Thanks

try this
<ComboBox Height="23" HorizontalAlignment="Left" Margin="47,128,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" ItemsSource="{Binding ObsCompanyCollection,Mode=OneWay}"

Related

TreeViewItem template click/select/highlight issue

I am new to WinUI 3 and I am currently building a TreeView (CommunityToolkit) where I can drag/drop TreeViewItems on top of each other. The TreeViewItem that I have consist of 3 parts, a group name, a display name and children items. The drag/drop part of the code works fine, however there is an issue whereby clicking on an item doesn’t always select/highlight it and I cannot seem to find the root issue as to why. See image below.
In the image above, the first item is "selected" as I would like it to be with the blue highlight to the left. But when I click on either of the other 2 items (Level 1 or Level 2), I have observed the following behaviours.
A click on "U" or "Level 1" does not select the item. There is some "pressed" style showing, but once the mouse button is released nothing happens. There is no highlight or selected style present
A click just above or below the red line selects the item as I expect it to.
See the XAML below
<Grid>
<Border BorderThickness="2" BorderBrush="DimGray">
<TreeView AllowDrop = "True"
CanDragItems="True"
CanReorderItems = "False"
ItemsSource="{x:Bind Items}"
SelectedItem="{x:Bind SelectedDemoItem, Mode=TwoWay}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="local:DemoItem">
<TreeViewItem AllowDrop="True"
CanDrag="True"
CollapsedGlyph=""
ExpandedGlyph=""
IsExpanded="True"
ItemsSource="{x:Bind Children}"
Padding="-10,0,0,0">
<TreeViewItem.Content>
<StackPanel AllowDrop="True"
BorderBrush="Red"
BorderThickness="1"
CanDrag="True"
Orientation="Horizontal">
<TextBlock FontSize="14"
FontWeight="ExtraBold"
IsColorFontEnabled="True"
Margin="0,0,10,0"
MinWidth="30"
TextAlignment="Center"
Text="{x:Bind Group}" />
<TextBlock Text="{x:Bind DisplayName}" Margin="0,0,5,0"/>
</StackPanel>
</TreeViewItem.Content>
</TreeViewItem>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Border>
</Grid>
And the code-behind
public sealed partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
FillData();
}
private void FillData()
{
var level0 = new DemoItem { DisplayName = "Level 0", Group = Groups.M };
var level1 = new DemoItem { DisplayName = "Level 1", Group = Groups.U };
var level2 = new DemoItem { DisplayName = "Level 2", Group = Groups.C };
level1.Children.Add(level2);
level0.Children.Add(level1);
Items.Add(level0);
Items.Add(level0);
}
public ObservableCollection<DemoItem> Items { get; } = new();
public DemoItem SelectedDemoItem { get; set; }
}
public enum Groups
{
S, M, U, C
}
public class DemoItem
{
public string DisplayName { get; set; }
public ObservableCollection<DemoItem> Children { get; } = new();
public Groups Group { get; set; }
}
For the purpose of this test, I have removed all drag/drop code as they have no affect on the problem above. However, it may help to mention that I have seen this problem occur only when CanDrag is set to True within my item template.
Any help to fix this will be greatly appreciated.
Click events won't reach the TreeViewItem because of the TextBlocks. The easiest way is to disable IsHistTestVisible on both TextBlocks.
<TextBlock
MinWidth="30"
Margin="0,0,10,0"
FontSize="14"
FontWeight="ExtraBold"
IsColorFontEnabled="True"
IsHitTestVisible="False"
Text="{x:Bind Group}"
TextAlignment="Center" />
<TextBlock
Margin="0,0,5,0"
IsHitTestVisible="False"
Text="{x:Bind DisplayName}" />

Binding an ExpanderView do a viewModel?

I made some ExpanderViews and hardcoded everything. That worked and looked nice so I wanted to clean up and only write one ExpanderView in xaml and load everything else with a binding.
As far as I understood I need a ListBox around the whole thing to make it more dynamic?
This is my code so far:
<ListBox ItemsSource="{Binding ContactDe}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<toolkit:ExpanderView Header="{Binding}"
ItemsSource="{Binding LocationName}"
IsNonExpandable="False">
<toolkit:ExpanderView.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding LocationName}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" LineHeight="{StaticResource LongListSelectorGroupHeaderFontSize}" />
</DataTemplate>
</toolkit:ExpanderView.HeaderTemplate>
<toolkit:ExpanderView.ExpanderTemplate>
<DataTemplate>
<TextBlock Text="test" />
</DataTemplate>
</toolkit:ExpanderView.ExpanderTemplate>
<toolkit:ExpanderView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Information}" />
</DataTemplate>
</toolkit:ExpanderView.ItemTemplate>
</toolkit:ExpanderView>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The ContactViewModel-Class:
public class ContactDeViewModel : INotifyPropertyChanged
{
private string _locationName;
public string LocationName
{
get
{
return _locationName;
}
set
{
if (value != _locationName)
{
_locationName = value;
NotifyPropertyChanged("LocationName");
}
}
}
private List<string> _information;
public List<string> Information
{
get
{
return _information;
}
set
{
if (value != _information)
{
_information = value;
NotifyPropertyChanged("Information");
}
}
}
}
And this is where I fill the ContactViewModel:
this.ContactDe.Add(new ContactDeViewModel()
{
LocationName = "Stuttgart",
Information = new List<string>
{
"some text"
}
}
);
this.ContactDe.Add(new ContactDeViewModel()
{
LocationName = "Böblingen",
Information = new List<string>
{
"more text"
}
}
);
I made a SampleViewModel-File where I have:
<vm:MainViewModel.ContactDe>
<vm:ContactDeViewModel LocationName="Location 1" />
<vm:ContactDeViewModel LocationName="Location 2" />
</vm:MainViewModel.ContactDe>
In the preview-window it shows me 2 ExpanderViews with Location 1 and 2. But the same code doesn't work with the emulator or a real device. I don't really understand which Binding-Acces does what. It would already help me a lot if I could see a full example. I googled many tutorials but most only show 1 side, like a xaml without seing how the data is stored.
edit:
Now I edited the viewModel, so it's not a List<string> but a List<Info> with Info only containing string Text. So now I can say ItemsSource="{Binding Text}" which should be only 1 string at a time, right?
As stated in comment to #dellywheel's answer, that you set DataContext this way :
d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
that set DataContext for use in design-time only, hence it doesn't work in run-time. To set DataContext with similar approach for use in run-time, you can try this way :
<ListBox ItemsSource="{Binding ContactDe}">
<ListBox.DataContext>
<vm:MainViewModel/>
</ListBox.DataContext>
........
........
</ListBox>
or this way to set DataContext in page level :
<phone:PhoneApplicationPage>
<phone:PhoneApplicationPage.DataContext>
<vm:MainViewModel/>
</phone:PhoneApplicationPage.DataContext>
........
........
</phone:PhoneApplicationPage>
Another suggestion, prefer ObservableCollection rather than List for use along with data binding. ObservableCollection automatically notify view to refresh whenever item added to or removed from collection.
You need to change your bindings slightly
<toolkit:ExpanderView Header="{Binding LocationName}"
ItemsSource="{Binding Information}"
IsNonExpandable="False">
<toolkit:ExpanderView.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{StaticResource honeFontFamilySemiBold}" LineHeight="{StaticResource LongListSelectorGroupHeaderFontSize}" />
</DataTemplate>
</toolkit:ExpanderView.HeaderTemplate>
<toolkit:ExpanderView.ExpanderTemplate>
<DataTemplate>
<TextBlock Text="test" />
</DataTemplate>
</toolkit:ExpanderView.ExpanderTemplate>
<toolkit:ExpanderView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</toolkit:ExpanderView.ItemTemplate>
</toolkit:ExpanderView>
Hope that helps

LongListMultiSelector: How to use it with MVVM

I am displaying a list of cities using LongListMultiSelector with Grouping. My ViewModel has DataList propery which is bind to LongListMultiSelector.
On a button click event, i want to remove an item from LongListMultiSelector and also want to update the UI at same time. I don't understand from where should i remove an item so that because of MVVM, UI gets updated automatically.
Below is my CS code.
public class City
{
public string Name { get; set; }
public string Country { get; set; }
public string Language { get; set; }
}
public class Group<T> : List<T>
{
public Group(string name, IEnumerable<T> items)
: base(items)
{
this.Title = name;
}
public string Title
{
get;
set;
}
}
public class myVM : INotifyPropertyChanged
{
static List<City> cityList;
public List<Group<City>> _datalist;
public List<Group<City>> DataList
{
get
{
_datalist = GetCityGroups();
return _datalist;
}
set
{
_datalist = value;
OnPropertyChanged("DataList");
}
}
private static IEnumerable<City> GetCityList()
{
cityList = new List<City>();
cityList.Add(new City() { Name = "Milan", Country = "IT", Language = "Italian" });
cityList.Add(new City() { Name = "Roma", Country = "IT", Language = "Italian" });
cityList.Add(new City() { Name = "Madrid", Country = "ES", Language = "Spanish" });
return cityList;
}
private List<Group<City>> GetCityGroups()
{
IEnumerable<City> cityList = GetCityList();
return GetItemGroups(cityList, c => c.Country);
}
private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
{
IEnumerable<Group<T>> groupList = from item in itemList
group item by getKeyFunc(item) into g
orderby g.Key
select new Group<T>(g.Key, g);
return groupList.ToList();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Below is my XAML code
<Button Content="bind" Width="150" Height="150" VerticalAlignment="Bottom" Click="Button_Click"></Button>
<toolkit:LongListMultiSelector x:Name="AddrBook"
ItemsSource="{Binding DataList}"
EnforceIsSelectionEnabled="True"
JumpListStyle="{StaticResource AddrBookJumpListStyle}"
IsSelectionEnabled="True"
Background="Transparent"
GroupHeaderTemplate="{StaticResource AddrBookGroupHeaderTemplate}"
ItemTemplate="{StaticResource AddrBookItemTemplate}"
LayoutMode="List"
IsGroupingEnabled="true"
HideEmptyGroups ="true"/>
In phone:PhoneApplicationPage.Resources i have below xaml
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="AddrBookItemTemplate">
<StackPanel VerticalAlignment="Top">
<TextBlock Text="{Binding Name, Mode=TwoWay}" />
<TextBlock Text="{Binding Language, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="AddrBookGroupHeaderTemplate">
<Border Background="Transparent" Margin="12,8,0,8">
<Border Background="{StaticResource PhoneAccentBrush}"
Padding="8,0,0,0" Width="62" Height="62"
HorizontalAlignment="Left">
<TextBlock Text="{Binding Title, Mode=TwoWay}" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="48" Padding="6"
FontFamily="{StaticResource PhoneFontFamilySemiLight}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Border>
</Border>
</DataTemplate>
<phone:JumpListItemBackgroundConverter x:Key="BackgroundConverter"/>
<phone:JumpListItemForegroundConverter x:Key="ForegroundConverter"/>
<Style x:Key="AddrBookJumpListStyle" TargetType="phone:LongListSelector">
<Setter Property="GridCellSize" Value="113,113"/>
<Setter Property="LayoutMode" Value="Grid" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource BackgroundConverter}}" Width="Auto" Height="Auto" Margin="6" >
<TextBlock Text="{Binding Title, Mode=TwoWay}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" FontSize="48" Padding="6"
Margin="8,0,0,0" Foreground="{Binding Converter={StaticResource ForegroundConverter}}" VerticalAlignment="Bottom"/>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</phone:PhoneApplicationPage.Resources>
You simply remove the item from your DataList inside your VM.
The tricky part is to handle the SelectedItems of the MultiSelector since it isnt bindable.
The simplest solution for me was to hook up a command to the SelectionChanged event and pass the SelectedItems as a parameter with it (I used the Command class from the MvvmLight Toolkit for that). Inside the Command I check for any changes between the updated List and the old List in the VM.
Also you shouldn't use the Click Event on the button, in MVVM the Command Property is used along with the CommandParameter if needed.
For other Controls that dont have a build-in Command Property you can use something like the aforementioned class from the toolkit (or other MVVM frameworks).
Other things to notice:
You need to use something like an ObservableCollection instead of a List if you want the UI to automatically update after changes to the collection.
Also you cant actually remove anything from your DataList since your always re-reading your hardcoded items.

Silverlight ComboBox in DataGrid Binding SelectedItem problem

I have a combobox in datagrid.I use Silverlight 4.0 and MVVM.
My code works fine,unless when I removed a record from datagrid and add another one, the SelectedValue binding for combobox in added row doesnt work.
<sdk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items, Mode=TwoWay}" Name="dataGrid2" >
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Width="50*">
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=Products, Mode=OneWay}"
SelectedValue="{Binding Path=ProductId,Mode=TwoWay}"
DisplayMemberPath="ProductTitle"
SelectedValuePath="ProductId"/>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
Thanks
Found this piece of code on some site, it helped me in a similar Situation:
public class ComboBoxEx : ComboBox
{
protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var bindingExpression = GetBindingExpression(SelectedValueProperty);
base.OnItemsChanged(e);
if (bindingExpression != null)
{
var binding = bindingExpression.ParentBinding;
SetBinding(SelectedValueProperty, bindingExpression.ParentBinding);
}
}
}

Dynamically Changing Combobox to TextBox in datagrid inside Cell Editing Template in silverlight 4

I'm making an application in Silverlight 4. I am facing a problem, I need to change a particular combobox into textbox programmatically when a particular column value(using combobox) of the same row is changed.I need to change this on event cellEditEnded.
Please note that I need to change celleditingtemplate combobox to textbox not celltemplate textblock.
This my Column where I need to take the decision of its combo box selected value.
<sdk:DataGridTemplateColumn Header="Instruction Type"
CanUserResize="False" CanUserReorder="False">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding operationType}" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="instruction" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
This Column comboBox need to change to textbox here:
<sdk:DataGridTemplateColumn Header="Destination">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding destination}" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="destination"/>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
C# code:
public class Instruction
{
public string operationType { get; set; }
public string destination { get; set; }
}
private void myGrid_CellEditEnded(object sender, DataGridCellEditEndedEventArgs e)
{
DataGrid obj = (DataGrid)sender;
Instruction obj1 = (Instruction)obj.SelectedItem;
if (e.Column.Header.ToString() == "Instruction Type")
{
if (obj1.operationType == "ADD" || obj1.operationType == "SUB")
{
// Here I need Require Code ????/
}
}
}
I m waitng for anyone Genius who help me out ..
Here is a working example http://anzensoft.smtp.ru/FlashKiller2/DataGridTrickTestPage.html
And here is the source code http://cid-a1de71e9f2ae2f82.office.live.com/self.aspx/.Public/DataGridTrick.zip
xaml code
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid x:Name="dataGrid1" AutoGenerateColumns="False"
PreparingCellForEdit="dataGrid1_PreparingCellForEdit">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Instruction Type">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding operationType}" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="instruction"
SelectedValue="{Binding operationType, Mode=TwoWay}">
<s:String>ADD</s:String>
<s:String>MUL</s:String>
</ComboBox>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn Header="Destination">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding destination}" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<Grid>
<ComboBox x:Name="destinationComboBox"
SelectedValue="{Binding destination, Mode=TwoWay}">
<s:String>sdas</s:String>
<s:String>dasdasdasd</s:String>
</ComboBox>
<TextBox x:Name="destinationTextBox"
Text="{Binding destination, Mode=TwoWay}"
Visibility="Collapsed"/>
</Grid>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
C# code
namespace DataGridTrick
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
dataGrid1.ItemsSource = new List<Instruction>()
{
new Instruction(){operationType = "ADD", destination ="sdas"},
new Instruction(){operationType = "ADD", destination = "dasdasdasd"}
};
}
private void dataGrid1_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
if ((string)e.Column.Header == "Destination")
{
var tb = e.EditingElement.FindName("destinationTextBox") as TextBox;
var cb = e.EditingElement.FindName("destinationComboBox") as ComboBox;
var instruction = e.EditingElement.DataContext as Instruction;
if (tb == null || cb == null || instruction == null)
{
throw new
Exception("Something wrong here.. this dosen't have to happen!!");
}
else
{
if (instruction.operationType == "MUL")
{
tb.DataContext = e.EditingElement.DataContext;
cb.DataContext = null;
tb.Visibility = System.Windows.Visibility.Visible;
cb.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
tb.DataContext = null;
cb.DataContext = e.EditingElement.DataContext;
tb.Visibility = System.Windows.Visibility.Collapsed;
cb.Visibility = System.Windows.Visibility.Visible;
}
}
}
}
}
public class Instruction
{
public string operationType { get; set; }
public string destination { get; set; }
}
}