I have a strange problem in my WinRT/C# XAML Metro app, using the Windows 8 Release Preview (latest patches installed). I'm using a ComboBox, whose values ItemsSource and SelectedValue are bound to properties in a ViewModel:
<ComboBox SelectedValue="{Binding MySelectedValue, Mode=TwoWay}"
ItemsSource="{Binding MyItemsSource, Mode=OneWay}"
Width="200" Height="30" />
Code behind:
public MainPage()
{
this.InitializeComponent();
DataContext = new TestViewModel();
}
And a very simple definition of the TestViewModel, using strings:
public class TestViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private IEnumerable<string> _myItemsSource = new List<string>
{
"Test Item 1",
"Test Item 2",
"Test Item 3"
};
public IEnumerable<string> MyItemsSource
{
get { return _myItemsSource; }
}
private string _mySelectedValue = "Test Item 2";
public string MySelectedValue
{
get { return _mySelectedValue; }
set
{
_mySelectedValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MySelectedValue"));
}
}
}
}
Now I thought this simple solution should just work... But when I start the app, the SelectedValue="Test Item 2" doesn't show up, the ComboBox is left empty. By setting breakpoints I noticed that the bound values MyItemsSource and MySelectedValue are corectly retrieved from the View Model when I set the DataContext of the view. After this action, the ComboBox.SelectedValue property is actually set to "Test Item 2", but it just doesn't show! Also I noticed that when I change the selected value in the ComboBox by user action on the UI, the changed value shows up in the ComboBox and the View Model property is updated accordingly. So everything seems to work fine except the initial visualization of the MySelectedValue View Model property. I'm becoming really desperate about that...
Now while this is the simplest example, in the origin I wanted to bind whole entities to ComboBox, setting DisplayMemberPath and SelectedValuePath. Unfortunately, the same problem occurs.
I found the problem in my example: In the XAML markup I've defined the SelectedValue property before the ItemsSource property. If I swap both definitions in this way, it works:
<ComboBox ItemsSource="{Binding MyItemsSource, Mode=OneWay}"
SelectedValue="{Binding MySelectedValue, Mode=TwoWay}"
Width="200" Height="30" />
This is really odd and annoying. Now I would like to know: is this a bug or by design? I think this is a bug, because the control should be working regardless of the order of the defined properties in XAML.
this is working solution : you can find here https://skydrive.live.com/?cid=b55690d11b67401d&resid=B55690D11B67401D!209&id=B55690D11B67401D!209
<ComboBox Width="300" Height="32" HorizontalAlignment="Left" DisplayMemberPath="Name"
VerticalAlignment="Top" ItemsSource="{Binding PersonCollection}"
SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"></ComboBox>
ViewModle class is
public class ViewModel:BaseViewModel
{
private Person selectedPerson;
public Person SelectedPerson {
get { return this.selectedPerson; }
set { this.selectedPerson = value;
this.RaisePropertyChanged("SelectedPerson");
}
}
public ObservableCollection<Person> PersonCollection { get; set; }
public ViewModel()
{
this.PersonCollection = new ObservableCollection<Person>();
this.PopulateCollection();
//setting first item as default one
this.SelectedPerson = this.PersonCollection.FirstOrDefault();
}
private void PopulateCollection()
{
this.PersonCollection.Add(new Person { Name="Oscar", Email="oscar#sl.net" });
this.PersonCollection.Add(new Person { Name = "Jay", Email = "jay#sl.net" });
this.PersonCollection.Add(new Person { Name = "Viral", Email = "viral#sl.net" });
}
}
Related
I have created a simple UWP app. All I want is, whenever the user clicks on the AutoSuggestBox, it needs to show all the items in the ItemsSource as suggestions. A combobox is working fine when I set the DisplayMemberPath but the AutoSuggestBox upon clicking doesn't show the ItemsSource as suggestions. Please help. (In this case when I click on the AutoSuggestBox, it needs to display ABC, BCD)
xaml: MainPage.xaml
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<ComboBox Width="120"
ItemsSource="{Binding TestList,Mode=OneWay}"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<AutoSuggestBox Width="200"
Margin="0,20,0,0"
ItemsSource="{Binding TestList,Mode=OneWay}"
DisplayMemberPath="Name"
TextMemberPath="Name"
PlaceholderText="Search"/>
</StackPanel>
Code Behind: MainPage.xaml.cs
public class Test
{
public string Name { get; set; }
public int Id { get; set; }
}
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private List<Test> _testList;
public List<Test> TestList
{
get
{
_testList = new List<Test>();
_testList.Add(new Test()
{
Name = "ABC",
Id = 1,
});
_testList.Add(new Test()
{
Name = "BCD",
Id = 2,
});
return _testList;
}
}
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
}
}
In this case when I click on the AutoSuggestBox, it needs to display ABC, BCD
Please refer AutoSuggestBox document, Represents a text control that makes suggestions to users as they enter text using a keyboard or pen (using ink and handwriting recognition). it will filter your data based on the input. Then, set the filtered data as the ItemsSource of the AutoSuggestBox to update the suggestion list. So the drop list only rendered when you typing. and it will not display the drop-list when you click the AutoSuggestBox.
For this scenario, the best practice is using ComboBox to replace.
I'm attempting to get my head around MVVM with XamarinForms and I'm slightly confused with regards to proper partitioning of functionality:
I have a main page, MainPage.xaml, which includes a stacklayout:
<StackLayout x:Name="MainPageStackLayout">
...
</StackLayout>
Within this stacklayout I have Picker which is bound as follows:
<Picker Title="Select a background colour"
TitleColor="Black"
TextColor="Black"
ItemsSource="{Binding MyColours}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding selectedBackGroundColour}" SelectedIndexChanged="BackGroundColourPicker_SelectedIndexChanged"/>
Following the article from microsoft (https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/userinterface-monkeyapppicker/):
I have a "View" which basically defines the layout of my page.
A "ViewModel" which holds an IList "MyColours" and a variable "SelectedBackGroundColour".
A "Model" which defines the MyColour class. A MyColour has a string name and a Xamarin.Forms.Color (from a hex value, both populated on start up).
This all works fine. I can start up the app and the Picker populates with the colours I add to "MyColours". If I change the index then my SelectedBackGroundColour also updates, has the correct name and a different RGB value.
However, I'm lost as to where I would tie in the updating of the actual background colour of the MainPageStackLayout. The View (MainPage.xaml.cs) picks up the "BackGroundColourPicker_SelectedIndexChanged" event but what is the standard practice for reading from the view model (where SelectedBackGround colour is actual defined ?)
I have a feeling I can bind Background colour in the MainPageStackLayout xaml view so I wont have to catch the selected index change event.
Thanks all.
According to your description, I guess that you want to change MainPage StackLayout BackGround color by Picker value, am I right?
If yes, please follow the steps below.
Firstly, please confirm that you implement INotifyPropertyChanged interface to notify SelectedBackGroundColour changed.
Then there are full code, please take a look:
<StackLayout x:Name="MainPageStacklayout" BackgroundColor="{Binding selectedBackGroundColour.color}">
<Picker
x:Name="picker1"
Title="Select a background colour"
ItemDisplayBinding="{Binding name}"
ItemsSource="{Binding MyColours}"
SelectedItem="{Binding selectedBackGroundColour}"
TextColor="Black"
TitleColor="Black" />
</StackLayout>
public partial class Page5 : ContentPage, INotifyPropertyChanged
{
public ObservableCollection<MyColour> MyColours { get; set; }
private MyColour _selectedBackGroundColour;
public MyColour selectedBackGroundColour
{
get { return _selectedBackGroundColour; }
set
{
_selectedBackGroundColour = value;
RaisePropertyChanged("selectedBackGroundColour");
}
}
public Page5()
{
InitializeComponent();
MyColours = new ObservableCollection<MyColour>()
{
new MyColour(){name="red",color=Color.Red},
new MyColour(){name="gray",color=Color.Gray},
new MyColour(){name="BlueViolet",color=Color.BlueViolet}
};
selectedBackGroundColour = MyColours[0];
this.BindingContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class MyColour
{
public string name { get; set; }
public Color color { get; set; }
}
The screenshot:
I'm trying to create a MenuFlyout with ToggleMenuFlyoutItems where one and only one toggle is checked at any given moment. The toggles corresponds to ToggleViewModels, binding the IsChecked property of the toggle to an IsSelected property of the ToggleViewModel. Because I want to uncheck the previously checked toggle whenever a new toggle is checked I relay the setting of the IsSelected property to the MainViewModel that holds the collection of ToggleViewModels.
Button with flyout defined in MainPage.xaml
<Button Content="Asdf">
<Button.Flyout>
<MenuFlyout>
<ToggleMenuFlyoutItem
Text="{x:Bind _viewModel.ToggleCollection[0].Name}"
IsChecked="{x:Bind _viewModel.ToggleCollection[0].IsSelected, Mode=TwoWay}" />
<ToggleMenuFlyoutItem
Text="{x:Bind _viewModel.ToggleCollection[1].Name}"
IsChecked="{x:Bind _viewModel.ToggleCollection[1].IsSelected, Mode=TwoWay}" />
<ToggleMenuFlyoutItem
Text="{x:Bind _viewModel.ToggleCollection[2].Name}"
IsChecked="{x:Bind _viewModel.ToggleCollection[2].IsSelected, Mode=TwoWay}" />
</MenuFlyout>
</Button.Flyout>
</Button>
MainPageViewModel:
public class MainViewModel : BindableBase
{
public MainViewModel()
{
ToggleCollection = new ObservableCollection<ToggleViewModel>();
var selectToggleAction = new Action<ToggleViewModel>(param => SetToggleSelection(param));
for (int i = 0; i < 3; i++)
{
ToggleCollection.Add(new ToggleViewModel($"Item {i}", selectToggleAction));
}
}
public ObservableCollection<ToggleViewModel> ToggleCollection { get; private set; }
private void SetToggleSelection(ToggleViewModel toggle)
{
var selectedToggle = ToggleCollection.SingleOrDefault(t => t.IsSelected);
if (selectedToggle != toggle)
{
selectedToggle?.SetSelection(false);
toggle.SetSelection(true);
}
}
}
ToggleViewModel:
public class ToggleViewModel : BindableBase
{
private Action<ToggleViewModel> _selectToggleAction;
private bool _isSelected;
public ToggleViewModel(string name, Action<ToggleViewModel> action)
{
Name = name;
_selectToggleAction = action;
}
public string Name { get; set; }
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_selectToggleAction(this);
base.OnPropertyChanged();
}
}
}
public void SetSelection(bool selected)
{
_isSelected = selected;
base.OnPropertyChanged("IsSelected");
}
}
Now all the code above works very well. The problem occurs when I try to use regular bindings instead of compiled ones:
<ToggleMenuFlyoutItem
Text="{Binding ToggleCollection[0].Name}"
IsChecked="{Binding ToggleCollection[0].IsSelected, Mode=TwoWay}" />
Binding the properties like this I'm suddenly able to uncheck the currently checked toggle so that none is selected. This is due to the getter of the IsSelected property not being called when I raise the OnPropertyChanged in the setter of the IsSelected property (the reason for using regular bindings is that I want to create the toggles dynamically in code behind, but to illustrate the problem XAML works just as well).
Can anyone explain to me why the {x:Bind} in this case works but not the {Binding}?
I develop an application, and faced a problem with following part.
I have a 'textblock' that binds exact item in observable collection of items('Items') and shows the number. Each item has a property, called 'Count'.
When user taps current textblock, which is in stackpanel of longlistselector (binding Items), I need this textblock to show new number(idea is each time user taps textblock, number increases by 1).
The only method I discovered is each time Navigate to current pivot item(where textblock is situated) to force pivot item's reload data from observable collection, where updated items(and 'Count' property) are stored. But it is slow and doesn't work good.
Please, advice how to make the number appear in the textblock each time user taps on current textblock.
<phone:PivotItem Name="Documents" Header="Documents" Margin="0" >
<Grid>
<phone:LongListSelector ItemsSource="{Binding Items}" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Height="95" >
<TextBlock Tap="Plus_Tap" Visibility="Visible" Width="20" Height="50" Text="{Binding Count}" FontFamily="Segoe WP Light"
FontSize="35" Foreground="White" Margin="2,0,0,2"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</phone:PivotItem>
namespace PackMan
{
public partial class CategoryList : PhoneApplicationPage
{
public CategoryList()
{
InitializeComponent();
DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void Plus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
PackList selectedList = (sender as TextBlock).DataContext as PackList;
selectedList.Count += 1;
NavigationService.Navigate(new Uri("/CategoryList.xaml?Documents", UriKind.Relative));
}
}
}
How to refresh the data in pivot item after updating data through xaml UI?
here a guy in the very end of his posted answer to his own question wrote: "If you are using the observableCollection than no need to refresh the page. It is the magic of ViewModel." But I load data from 'Items' observable collection, which is not in ViewModel, but declared in Packlist.cs. Maybe this will help.
Here I do increase Count property of the item in ObservableCollection "Items" :
private void Plus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
PackList selectedList = (sender as TextBlock).DataContext as PackList;
selectedList.Count += 1;
I tap on textblock, and text of the textblock shows no changes. I tap return - which brings me back to menu page, than again I open pivot item page, and see the textblock's text(number) increases by one. Change is seen only when I reload page(pivot item), since I have this in its constructor and OnNavigatedTo method:
public CategoryList()
{
InitializeComponent();
DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
LoadData() - loads OBservable collection ("Items"), which has items, and Count as one of its properties:
public void LoadData()
{
this.Items = LoadNewLists();
this.IsDataLoaded = true;
}
Maybe now you could tell me how to make text of the textblock change instantly as I tap on it(textblock). I will be thankful for any advice, since this moment has stopped me from developing my app second day now.
I figured it out. I should have read about INotifyPropertyChanged Interface and created 'Count' property using this interface's method:
public int Count
{
get
{
return _count;
}
set
{
if (value != _count)
{
_count = value;
NotifyPropertyChanged("Count");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Hope it will be helpful to anyone.
I'd like to use a FlipView to display some items and start showing a specific item.
For this, I have defined a view model class:
class MyDataContext
{
public MyDataContext()
{
Items = new List<MyClass>();
Items.Add(new MyClass("1"));
Items.Add(new MyClass("2"));
Items.Add(new MyClass("3"));
SelectedItem = Items[1];
}
public List<MyClass> Items { get; set; }
public MyClass SelectedItem { get; set; }
}
As you can see, the selected item is not the first item.
Now for the XAML:
<FlipView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"></FlipView>
However, when I run the app, the flip view shows the first item, not the second item.
Is this intentional?, or is it a bug?
Try this
<FlipView
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
your SelectedItem needs to be a TwoWay binding for it to work, since the value is set by both the control and the view model.
Was having the same issue with the FlipView and unable to get the BindableBase or the TwoWay option to work. Because the order of the list was not really a topic for me, I've created a method to reorder the ItemsSource, to start with the SelectedItem as being the first item in the Collection.
In the underlying code, the result is the new ItemsSource for the FlipView, instead of the previous List elements.
public static List<T> ReorderList(List<T> elements, T selectedElement)
{
var elementIndex = elements.FindIndex(x => x.Id == selectedElement.Id);
var result = new List<T>();
foreach (var item in elements)
{
if (elementIndex .Equals(elements.Count))
{
elementIndex = 0;
}
result.Add(elements[elementIndex]);
elementIndex++;
}
return result;
}
On top of what Filip stated, you're class (MyDataContext) needs to notify the UI that the property has changed. Your ViewModel must implement INotifyPropertyChanged and the property needs to fire the PropertyChanged event
public class ViewModel : INotifyPropertyChanged
{
private object _selectedItem;
public object SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
}
You can also use the BindableBase class that comes with the sample apps
public class ViewModel : BindableBase
{
private object _selectedItem;
public object SelectedItem
{
get { return this._selectedItem; }
set { this.SetProperty(ref this._selectedItem, value); }
}
}
It's look like a bug.
If you debug your code you will notice that at first your SelectedItem in VM set to the right element, then it sets to null and after that it sets to the first element of FlipView's ItemsSource collection.
As a workaround I see setting SelectedItem of VM after Loaded event of FlipView is raised.