Listbox binding in Silverlight - data-binding

I have a listbox on silverlight page, the datacontext of the page is set to an instance -- TestQuestions, please see the code below. The listbox uses a DataTemplate and its ItemSource is 'Answers' which is a property of the page's DataContext, everything works fine until I try to bind to 'ShowAnswer', a property on the page's DataContext within the DataTemplate. No matter what I tried it won't pick the property's value.
Thank you all for your help.
Xaml:
<ListBox ItemsSource="{Binding Path=Answers, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton IsChecked="{Binding Path=Correct, Mode=TwoWay}" >
<Grid>
<StackPanel Visibility="{Binding Path=ShowAnswer}">
<Rectangle Fill="Blue" Visibility="{Binding Path=Correct}" />
</StackPanel>
<TextBlock Text="{Binding Path=AnswerText, Mode=TwoWay}" TextWrapping="Wrap" />
</Grid>
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
C#:
public class Answer
{
private bool correct = false;
public bool Correct
{
get { return correct; }
set
{
correct = value;
NotifyPropertyChanged("Correct");
}
}
private string answerText = false;
public string AnswerText
{
get { return answerText; }
set
{
answerText = value;
NotifyPropertyChanged("AnswerText");
}
}
}
public class TestQuestions
{
private ObservableCollection<Answer> answers = new ObservableCollection<Answer>();
public ObservableCollection<Answer> Answers
{
get { return answers; }
set
{
if (answers != value)
{
answers = value;
NotifyPropertyChanged("Answers");
}
}
}
private bool showAnswer = false;
public bool ShowAnswer
{
get { return showAnswer; }
set
{
showAnswer = value;
NotifyPropertyChanged("ShowAnswer");
}
}
}

It looks to me like you're trying to bind the UIElement.Visibility to a boolean value. Change your 'ShowAnswer' property from a boolean to a Visibility property and you should be set.
private Visibility showAnswer = Visibility.Collapsed;
public Visibility ShowAnswer
{
get { return showAnswer; }
set
{
showAnswer = value;
NotifyPropertyChanged("ShowAnswer");
}
}
EDIT:
If you are trying to bind to a property on the DataContext of the parent control, you could do this:
Name your UserControl
Example:
<UserControl x:Class="MvvmLightProto.MainPage"
x:Name="mainProtoPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="700"
Width="1200">
In the above example, the UserControl has the name of "mainProtoPage", now in your XAML, you could do this:
<StackPanel Visibility="{Binding DataContext.ShowAnswer, ElementName=mainProtoPage}">

Related

Xamarin Forms: How can i correctly bind data from two view models to a single view?

This is the short code for testing purpose. The problem is that the UI is not displaying the Text from the Label which is binded with ViewModelB. In debugging when I hover the mouse in xaml over the Text from the Label I see the right binding data is there, but the UI simply won't display. With ViewModelA there are no problems.
In XAML:
<StackLayout>
<StackLayout>
<StackLayout.BindingContext>
<testbinding:ViewModelA/>
</StackLayout.BindingContext>
<Button Command ="{Binding Get}"/>
</StackLayout>
<StackLayout>
<StackLayout.BindingContext>
<testbinding:ViewModelB/>
</StackLayout.BindingContext>
<Label Text="{Binding Metadata}"/>
</StackLayout>
ViewModelA: where BaseViewModel is a INotifyPropertyChanged interface
public ViewModelA:BaseViewModel
{
public ViewModelA()
{
Get = new Command(SendText);
vmB = new ViewModelB();
}
ViewModelB vmB;
public ICommand Get { get; }
private void SendText()
{
string data = "someText";
vmB.GetMetadata(data);
}
}
ViewModelB is like this:
class ViewModelB:BaseViewModel
{
private string _metadata = string.Empty;
public string Metadata
{
get { return _metadata; }
set
{
_metadata = value;
OnPropertyChanged();
}
}
GetMetadata()
{
Metadata = "Some text";
}
}
In ViewModelA there are more properties which I need and in ViewModelB is just one property which gets data from a function. I could make just one ViewModel from both of them which works fine, but I'm trying to keep them smaller and organized. I already tried so many scenarios and is getting really frustrating.
Thanks for helping.
In the second StackLayout in your xaml file you're not binding it's BindingContext property to the ViewModelB instance from ViewModelA but instead you are creating a new one.
Here's a working solution for you:
public class ViewModelA : BaseViewModel
{
public ViewModelB ViewModelB { get; }
public ICommand GetMetadataCommand { get; }
public ViewModelA()
{
ViewModelB = new ViewModelB();
GetMetadataCommand = new Command((_) => GetMetadata());
}
private void GetMetadata()
{
string data = "someText";
ViewModelB.GetMetadata(data);
}
}
public class ViewModelB : BaseViewModel
{
private string _metadata;
public string Metadata
{
get { return _metadata; }
set
{
_metadata = value;
OnPropertyChanged();
}
}
public void GetMetadata(string data)
{
Metadata = data;
}
}
XAMl:
<StackLayout>
<StackLayout x:Name="StackLayout1">
<StackLayout.BindingContext>
<local:ViewModelA />
</StackLayout.BindingContext>
<Button Command ="{Binding GetMetadataCommand}"/>
</StackLayout>
<StackLayout BindingContext="{Binding Source={x:Reference StackLayout1}, Path=BindingContext.ViewModelB}">
<Label Text="{Binding Metadata}" />
</StackLayout>
</StackLayout>

Xaml.Win8: How can I bind nested class to datatemplate?

I have custom element and want to change it content by selector.
It means:
<xamlExtensions:BitmapButton
Grid.Column="5"
Click="OnBuyButtonClicked"
Command="{Binding BuyCommand}" CommandParameter="{Binding}"
Style="{StaticResource BitmapButtonStyle}"
DisabledStateBitmap="ms-appx:///Assets/UI/Pages/MainPage/BuyCoinsPopup/disabledButton.png">
<xamlExtensions:BitmapButton.Content>
<ContentControl ContentTemplateSelector="{StaticResource ButtonSelector}" Content="{Binding ContentButton}">
</ContentControl>
</xamlExtensions:BitmapButton.Content>
</xamlExtensions:BitmapButton>
<DataTemplate x:Key="EnabledButtonTemplate">
<TextBlock FontWeight="Bold" FontSize="24" Text="{Binding Path =BuyText}"/>
</DataTemplate>
<DataTemplate x:Key="DisabledButtonTemplate" >
<TextBlock FontWeight="Bold" FontSize="18" Text="{Binding Path =NotAvaliable}"/>
</DataTemplate>
<DataTemplate x:Key="TimedButtontemplate" >
<StackPanel >
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Path= AvaliableInTitle}" HorizontalAlignment="Center" Foreground="Black"/>
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Path = Counter}" HorizontalAlignment="Center" Foreground="Black"/>
</StackPanel>
</DataTemplate>
<helpers1:ButtonDataTemplateSelector x:Key="ButtonSelector"
EnabledButtonTemplate="{StaticResource EnabledButtonTemplate}"
DisabledButtonTemplate="{StaticResource DisabledButtonTemplate}"
TimedButtontemplate="{StaticResource TimedButtontemplate}"/>
view model:
public class ContentButton : ObservableObject
{
private string _buyText = string.Empty;
private string _counter = "--:--";
private ButtonState _buttonState;
private string _avaliableInTitle = LocalizationManager.GetLocalizedString("AvaliableInTitle");
private string _notAvaliable = "Not avaliable";
public string BuyText
{
get { return _buyText; }
set
{
_buyText = value;
RaisePropertyChanged("BuyText");
}
}
public string NotAvaliable
{
get { return _notAvaliable; }
set
{
_buyText = value;
RaisePropertyChanged("NotAvaliable");
}
}
public string Counter
{
get { return _counter; }
set
{
_counter = value;
RaisePropertyChanged("Counter");
}
}
public ButtonState ButtonState
{
get
{
return _buttonState;
}
set
{
_buttonState = value;
RaisePropertyChanged("ButtonState");
}
}
public string AvaliableInTitle
{
get { return _avaliableInTitle; }
set
{
_avaliableInTitle = value;
RaisePropertyChanged("AvaliableInTitle");
}
}
}
public class StorePopupTileItem : TileItem
{
private ContentButton _contentButton;
public ContentButton ContentButton
{
get
{
return _contentButton;
}
set
{
_contentButton = value;
RaisePropertyChanged("ContentButton");
}
}
}
I am binding StorePopupTileItem; and when I change one of properties (AvaliableInTitle, BuyText or else) it doesn't change on the view.
How can I fix it?
Thanks
Added:
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (item != null)
{
var itemCur = (ContentButton)item;
switch (itemCur.ButtonState)
{
case ButtonState.Disabled:
return DisabledButtonTemplate;
case ButtonState.TimeDisabled:
return TimedButtontemplate;
case ButtonState.Enabled:
return EnabledButtonTemplate;
}
}
return EnabledButtonTemplate;
but I don't know what to do if I change only one field (f.e. ButtonState) from the code side?
In this case new information doesn't bind. And right now in every point where I want to update button I need to do this:
StorePopupTileItem tempItem = TileItem;
TileItem.ContentButton = new ContentButton
{
BuyText = tempItem.ContentButton.BuyText,
ButtonState = ButtonState.Enabled,
Counter = tempItem.ContentButton.Counter
}

ComboBox selectedItem affect another ComboBox

I have a question about Databinding which I'm really struggling to understand. I have two ComboBox on my extended splash screen. What I want to achieve is when you select an item from the first ComboBox, the items in the 2nd ComboBox should change. Please see the code below.
First let me try to explain how my Data looks like and what problem I'm facing.
Collection
A
AA
AB
AC
B
BA
BB
C
CA
The First ComboBox should show A,B and C as items. Now lets say you selected A, the ComboBox 2 should show AA,AB and AC as items. The problem I have is that ComboBox 2 is showing AA only not all 3 items.
My ViewModel Called MainViewModel looks like this:-
public class ItemViewModel : INotifyPropertyChanged
{
private string _befattning;
public string Befattning
{
get
{
return _befattning;
}
set
{
if (value != _befattning)
{
_befattning = value;
NotifyPropertyChanged("Befattning");
}
}
}
private string _befattning2;
public string Befattning2
{
get
{
return _befattning2;
}
set
{
if (value != _befattning2)
{
_befattning2 = value;
NotifyPropertyChanged("Befattning2");
}
}
}
private string _befattning3;
public string Befattning3
{
get
{
return _befattning3;
}
set
{
if (value != _befattning3)
{
_befattning3 = value;
NotifyPropertyChanged("Befattning3");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
//NotifyPropertyChanged Code
}
}
public class MainViewModelGroups : INotifyPropertyChanged
{
public MainViewModelGroups(String enhet)
{
this._enhetsNamn = enhet;
}
private string _enhetsNamn;
public string EnhetsNamn
{
get { return _enhetsNamn; }
}
private string _selectedItem;
public string SelectedItem
{
get { return _selectedItem; }
set
{
if (value != _selectedItem)
{
_selectedItem = value;
NotifyPropertyChanged("SelectedItem");
}
}
}
private ObservableCollection<ItemViewModel> _items = new ObservableCollection<ItemViewModel>();
public ObservableCollection<ItemViewModel> Items
{
get
{
return this._items;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
//NotifyPropertyChangedCode
}
}
public sealed class MainViewModel
{
private static MainViewModel _mainViewModel = new MainViewModel();
private ObservableCollection<MainViewModelGroups> _collection = new ObservableCollection<MainViewModelGroups>();
public ObservableCollection<MainViewModelGroups> Collection
{
get { return this._collection; }
}
public MainViewModel()
{
var enhet1 = new MainViewModelGroups("Akutmottagning");
enhet1.Items.Add(new ItemViewModel() { Befattning = "Ledningsansvarig sjuksköterska" });
Collection.Add(enhet1);
}
And my XAML code looks like this
<ComboBox x:Name="EnhetLista"
ItemsSource="{Binding Collection}"
SelectedItem="{Binding SelectedItem, Mode=OneWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EnhetsNamn}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox x:Name="BefattningsLista"
DataContext="{Binding ElementName=EnhetLista, Path=SelectedItem, Mode=OneWay}"
ItemsSource="{Binding Path=Items, Mode=OneWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Can someone please helps by explaining what is wrong with my code and how to achieve my goal?
Add a second ObservableCollection to your viewmodel, then change that based on the selected item.
public sealed class MainViewModel
{
private static MainViewModel _mainViewModel = new MainViewModel();
private ObservableCollection<MainViewModelGroups> _collection = new ObservableCollection<MainViewModelGroups>();
public ObservableCollection<MainViewModelGroups> Collection
{
get { return this._collection; }
}
public ObservableCollection<ItemViewModel> Items
{
get { return this._items; }
set { this._items = value; OnPropertyChanged("Items"); }
}
public MainViewModelGroups SelectedGroup
{
get { return this._selectedGroup; }
set { this._selectedGroup = value; Items = value.Items; }
}
public MainViewModel()
{
var enhet1 = new MainViewModelGroups("Akutmottagning");
enhet1.Items.Add(new ItemViewModel() { Befattning = "Ledningsansvarig sjuksköterska" });
Collection.Add(enhet1);
}
}
Your Xaml will change to:
<ComboBox x:Name="EnhetLista"
ItemsSource="{Binding Collection}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EnhetsNamn}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox x:Name="BefattningsLista"
ItemsSource="{Binding Path=Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Your viewmodel may need to implement INotifyPropertyChanged. It may not though, as ObservableCollection may take care of that for you.

Dynamic binding with User Control does not work as Static is working in Silverlight and MVVM

I have created sample User Control
RestrictedBox.xaml
<UserControl.Resources>
<Converters:EnumToVisibilityConverter x:Key="enumToVisConverter" />
<Converters:EnumToVisibilityConverterReverse x:Key="enumToVisConverterReverse" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" Width="Auto">
<StackPanel Margin="0">
<TextBox Text="{Binding Value}" Visibility="{Binding Type,Converter={StaticResource enumToVisConverter}}" BorderBrush="Green" />
<PasswordBox Password="{Binding Value}" Visibility="{Binding Type,Converter={StaticResource enumToVisConverterReverse}}" BorderBrush="Red" />
</StackPanel>
</Grid>
RestrictedBox.xaml.cs
public partial class RestrictedBox : UserControl
{
public RestrictedBox()
{
InitializeComponent();
//If i bind static value and uncomment following line then it is working.
//If i bind static value and comment following line then it is not working
this.DataContext = this;
//Dynamic binding does not work using this code.
}
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(RestrictedBox), new PropertyMetadata("", ValueChanged));
private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
public Mode Type
{
get { return (Mode)GetValue(TypeProperty); }
set { SetValue(TypeProperty, value); }
}
public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(Mode), typeof(RestrictedBox), new PropertyMetadata(TypeChanged));
private static void TypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
}
LoginViewModel.cs
public class LoginViewModel : INotifyPropertyChanged, IRegionMemberLifetime
{
private string _UserName = "Imdadhusen Sunasara";
public string UserName
{
get { return _UserName; }
set
{
_UserName = value;
OnPropertyChanged("UserName");
}
}
}
LoginView.xaml (This following line does not work with binding)
<control:RestrictedBox Value="{Binding UserName}" Type="Text" />
This is working (with static binding)
<control:RestrictedBox Value="Imdadhusen" Type="Text" />
Thanks,
Imdadhusen
Actually It should work. Can you please verify that the DataContext of parent container of below control doesn't refering to any other property of viewmodel.
<control:RestrictedBox Value="Imdadhusen" Type="Text" />
eg. Something like below.
<StackPanel DataContext={Binding CurrentUser}>
<control:RestrictedBox Value="{Binding UserName}"
Type="Text" />
</StackPanel>
May be this help you....
I have got solution from following
http://forums.silverlight.net/t/250206.aspx/1?Dynamic+binding+with+User+Control+does+not+work+as+Static+is+working+in+Silverlight+and+MVVM
Thanks everybody who trying to help me.
Imdadhusen

Displaying member in comboboxcolumn only after clicking column

I have a control, when I need dislay person with two column:
-fullname
-best friend
The problem is , that property BestFriend on Person is an object.
At start Person has his own BestFriend, but he can change it from combobox column.
Now, after control loaded the column with bestfriend is blank.
When I doubleclick at this column I can change bestfirend, and it sets bestfriend of this person.
But what I must to do to have at start not blank column?
I think, that the problem is, that control can't match bestfriend, with collection of bestfriend, so I think that I must match them by id, but I don't know how can I do ti.
<UserControl x:Class="MvvmLight1.MainPage"
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:telerik="http://schemas.telerik.com/2008/xaml/presentation" mc:Ignorable="d"
Height="300"
Width="300"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<telerik:RadGridView x:Name="grdSrL"
AutoGenerateColumns="False"
SelectionMode="Single"
IsReadOnly="False"
IsFilteringAllowed="True"
Height="386"
Width="460"
HorizontalAlignment="Left"
CanUserDeleteRows="False"
CanUserInsertRows="True"
CanUserReorderColumns="False"
CanUserResizeColumns="True"
ItemsSource="{Binding Persons}">
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn DataMemberBinding="{Binding FullName}" IsReadOnly="True" Header="FullName" />
<telerik:GridViewComboBoxColumn ItemsSource="{Binding Friends,Source={StaticResource Main}}" ItemsSourceBinding="{Binding Friends,Source={StaticResource Main}}" Header="1st"
DataMemberBinding="{Binding BestFriend}"
DisplayMemberPath="FullName" />
</telerik:RadGridView.Columns>
</telerik:RadGridView>
</Grid>
</UserControl>
the main model:
namespace MvvmLight1
{
public class Person:INotifyPropertyChanged
{
private string _fullName;
public string FullName
{
get { return _fullName; }
set
{
if (_fullName!=value)
{
_fullName = value;
OnPropertyChanged("FullName");
}
}
}
public int Id
{
get { return _id; }
set { _id = value; }
}
public Person BestFirend
{
get { return _bestFirend; }
set
{
if (_bestFirend!=value)
{
_bestFirend = value;
OnPropertyChanged("BestFirend");
}
}
}
private int _id;
private Person _bestFirend;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
and viewmodel:
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
namespace MvvmLight1.ViewModel
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
for (int i = 0; i < 3; i++)
{
var friend = new Person() {FullName = "Name" + (i + 3).ToString()};
_friends.Add(friend);
_persons.Add(new Person(){FullName = "Name"+i.ToString(),Id = i,BestFirend = friend});
}
}
private ObservableCollection<Person> _persons=new ObservableCollection<Person>();
public ObservableCollection<Person> Persons
{
get { return _persons; }
set
{
_persons = value;
}
}
public ObservableCollection<Person> Friends
{
get { return _friends; }
set
{
_friends = value;
}
}
private ObservableCollection<Person> _friends=new ObservableCollection<Person>();
}
}
and app xaml
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MvvmLight1.App"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:MvvmLight1.ViewModel"
mc:Ignorable="d">
<Application.Resources>
<!--Global View Model Locator-->
<vm:ViewModelLocator x:Key="Locator"
d:IsDataSource="True" />
<vm:MainViewModel x:Key="Main"/>
</Application.Resources>
</Application>
Not an expert on GridViewComboBoxColumn, but could it be that it is looking an instance of an object in the bound list, and that instance is not in it?
With "normal" ComboBoxes you got the choice whether you use value binding or item binding. In case of itembindng, the ComboBox looks for the same instance in the list of values. If it cannot find it it does not select any item.
In case of Valuebinding, the SelectedValue is compared to the value specified by SelectedValuePath. This then means that there is no requirement that the list entry and the selected entry are the same instance.
But as I said, this is for box standard ComboBoxes, as for the Telerik controls ... I don't really know. But from my experience with them (with WebForm controls) they are a helpful bunch, if you ask questions in their user support forums.

Resources