I am generating Grid for every item from my ObservableCollection. Now I want to be able to change the source collection at runtime and I am not sure what needs to be done.
Here is my XAML:
<Window.Resources>
<c:GraphicsList x:Key="GraphicsData" />
</Window.Resources>
...
...
<ItemsControl x:Name="icGraphics" ItemsSource="{Binding Source={StaticResource GraphicsData}}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Tag="{Binding id}" Margin="15,0,15,15">
<Label Grid.Row="0" Content="{Binding name}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And C#:
myCollection1 = this.FindResource("GraphicsData") as GraphicsList;
myCollection1:
public class GraphicsList : ObservableCollection<Graphics>
{
public GraphicsList()
{
}
}
Graphics class:
class Graphics: INotifyPropertyChanged
{
// some properties not important
}
Its a simplyfied version of my code, but it works, I basically a want to change the source collection myCollection1 to myCollection2 (which is same class just different list). How do I do this?
You can Add or Remove items from collection as below
var dresource = this.Resources["GraphicsData"] as GraphicsList;
dresource.Add(new Graphics() { Name = "New Entry" });
But with StaticResource you can't assign new Collection to one in ResourceDictionary.
Ideally you should be using ViewModel and bind Collection if you want to assign completely new collection.
Your mainwindow class or viewmodel should implement INotifyPropertyChanged interface
Sample code
public partial class MainWindow : Window, INotifyPropertyChanged
{
private GraphicsList _graphicsData;
public MainWindow()
{
InitializeComponent();
DataContext = this;
this.Loaded += MainWindow_Loaded;
}
public GraphicsList GraphicsData
{
get { return _graphicsData; }
set
{
if (Equals(value, _graphicsData)) return;
_graphicsData = value;
OnPropertyChanged("GraphicsData");
}
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
//var resource = this.Resources["GraphicsData"] as GraphicsList;
var resource = new GraphicsList();
resource.Add(new Graphics(){Name = "Some new Collection of data"});
this.GraphicsData = resource;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
And Your Xaml
<Grid>
<ListBox ItemsSource="{Binding GraphicsData}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I hope this will help
Related
I am trying to create a multi-select Combobox Custom control, This custom control should expose a dependency property called DropDownDataSource through which the user of the control can decide what day should bound to ComboBox. My code looks like this:
MainPage.Xaml
<Grid>
<local:CustomComboBox x:Name="customcb" DropDownDataSource="{x:Bind DropDownDataSource, Mode=OneWay}" Loaded="CustomControl_Loaded"> </local:CustomComboBox>
</Grid>
MainPage.Xaml.cs
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
private ObservableCollection<Item> _dropDownDataSource;
public ObservableCollection<Item> DropDownDataSource
{
get => _dropDownDataSource;
set
{
_dropDownDataSource = value;
OnPropertyChanged();
}
}
public MainPage()
{
this.InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void CustomControl_Loaded(object sender, RoutedEventArgs e)
{
var Items = new ObservableCollection<Item>(Enumerable.Range(1, 10)
.Select(x => new Item
{
Text = string.Format("Item {0}", x),
IsChecked = x == 40 ? true : false
}));
DropDownDataSource = Items;
}
}
Models
public class Item : BindableBase
{
public string Text { get; set; }
bool _IsChecked = default;
public bool IsChecked { get { return _IsChecked; } set { SetProperty(ref _IsChecked, value); } }
}
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetProperty<T>(ref T storage, T value,
[System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
{
if (!object.Equals(storage, value))
{
storage = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
CustomUserControl XAML
<Grid x:Name="GrdMainContainer">
<StackPanel Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBox Width="200" FontSize="24" Text="{Binding Header, Mode=TwoWay}"
IsReadOnly="True" TextWrapping="Wrap" MaxHeight="200" />
<ScrollViewer VerticalScrollBarVisibility="Auto" MaxHeight="200" Width="200" Background="White">
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Text}"
FontSize="24"
Foreground="Black"
IsChecked="{Binding IsChecked, Mode=TwoWay}"
IsThreeState="False" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
</Grid>
CustomUserControl Cs file
public sealed partial class CustomComboBox : UserControl
{
public CustomComboBox()
{
this.InitializeComponent();
}
public ObservableCollection<Item> DropDownDataSource
{
get { return (ObservableCollection<Item>)GetValue(DropDownDataSourceProperty); }
set { SetValue(DropDownDataSourceProperty, value); }
}
public static readonly DependencyProperty DropDownDataSourceProperty =
DependencyProperty.Register("DropDownDataSource", typeof(ObservableCollection<Item>), typeof(CustomComboBox), new PropertyMetadata("", HasDropDownItemUpdated));
private static void HasDropDownItemUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is CustomComboBox ucrcntrl)
{
var grd = UIElementExtensions.FindControl<Grid>(ucrcntrl, "GrdMainContainer");
grd.DataContext = ucrcntrl.DropDownDataSource as ObservableCollection<Item>;
}
}
}
All looks good to me, but for some reason, Dropdown is coming empty. Instead of the dependency property, If I assign a view model directly to the Control it works fine. But in my condition, it is mandatory that I have properties like DataSource,SelectedIndex, etc on the user control for the end-user to use. Can anyone point out what is going wrong here?
Here, I have attached a copy of my complete code.
I downloaded your sample code, the problem should be in the binding.
<ItemsControl ItemsSource="{Binding Items}">
This way of writing is not recommended. In the ObservableCollection, Items is a protected property and is not suitable as a binding property.
You can try to bind dependency property directly in ItemsControl:
<ItemsControl ItemsSource="{x:Bind DropDownDataSource,Mode=OneWay}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="local:Item">
<CheckBox IsChecked="{x:Bind IsChecked, Mode=TwoWay}"
IsThreeState="False" >
<TextBlock Text="{x:Bind Text}" Foreground="Black" FontSize="24"/>
</CheckBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
In addition, you may have noticed that I modified the style of CheckBox and rewritten the content to TextBlock, because in the default style of CheckBox, Foreground is not bound to the internal ContentPresenter.
Thanks.
I have been struggling with this for a day or so, can't figure out what I'm doing wrong here. I want to be able to select any tab in my observable collection of tabs, and I want my selection to be visible in the UI. I have tried SelectedIndex and SelectedItem. I can see that my Properties are set but my tabs are not selected, nothing happens in the UI. Here is my code:
MainWindow.xaml
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:WpfApplication5"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ViewModel xmlns="clr-namespace:WpfApplication5" />
</Window.DataContext>
<StackPanel>
<Button Content="Select Tab Index 0" Click="Button_Click_0"/>
<Button Content="Select Tab Index 1" Click="Button_Click_1"/>
<Label Content="{Binding SelectedIndex, UpdateSourceTrigger=PropertyChanged}" />
<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="{Binding SelectedIndex, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<uc:TabContent Content="{Binding Content}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</StackPanel>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_0(object sender, RoutedEventArgs e)
{
var viewModel = (ViewModel)DataContext;
viewModel.SelectedIndex = 0;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var viewModel = (ViewModel)DataContext;
viewModel.SelectedIndex = 1;
}
}
ViewModel.cs
class ViewModel
{
private int _selectedIndex = 0;
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<Tab> _tabCollection = new ObservableCollection<Tab>();
public ViewModel()
{
Tabs.Add(new Tab { Header = "Tab1", Content = new WpfApplication5.TabContent() });
Tabs.Add(new Tab { Header = "Tab2", Content = new WpfApplication5.TabContent() });
}
public ObservableCollection<Tab> Tabs
{
get { return _tabCollection; }
}
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
_selectedIndex = value;
NotifyPropertyChanged("SelectedIndex");
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Tab.cs
class Tab
{
public UserControl Content { get; set; }
public string Header { get; set; }
}
TabContent.xaml
<Grid>
<Label Content="Hello World!" />
</Grid>
Your ViewModel class doesn't implement the INotifyPropertyChanged interface:
class ViewModel : INotifyPropertyChanged
{
...
That's your issue.
Basically what i have is a ListBox with ContextMenu
<ListBox Margin="2,0,0,0" Grid.Row="1" ItemsSource="{Binding MyCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Style="{StaticResource NoVisualButton }" Tag="{Binding ID}" Width="430" toolkit:TiltEffect.IsTiltEnabled="True" Margin="0,0,0,12" Click="OnSelectWorkOutItemClick">
<StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="delete" Tag="{Binding ID}" Click="onContextMenuDeleteItemClick" IsEnabled="{Binding IsDeleteOptionEnable, ElementName=LayoutRoot}"/>
<toolkit:MenuItem Header="edit" Tag="{Binding ID}" Click="onContextMenuItemEditClick" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
...
</StackPanel>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
So if MyCollection has only one item, i have to disable delete MenuItem.
My model has a property
public bool IsDeleteOptionEnable
{
get
{
return MyCollection.Count() >= 2;
}
}
In the page i am setting the DataContext like:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (IsDataLoaded)
{
this.DataContext =MyModel;
}
}
The listbox is getting populated, but i can't disable "delete" MenuItem. What am i doing wrong?
Since the IsDeleteOptionEnable is a regular property, your view won't get notified when the property is changed. On options would be implementing INotifyPropertyChanged in your model (actually that should be ViewModel in an MVVM pattern) and calling the PropertyChanged event whenever items in your collection gets changed.
class YourModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
..
..
public YourModel() {
this.MyCollection = ...;
this.MyCollection.CollectionChanged += MyCollection_CollectionChanged;
}
public bool IsDeleteOptionEnable {
get {
return MyCollection.Count() >= 2;
}
}
private void MyCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
this.OnPropertyChanged("IsDeleteOptionEnable");
}
private void OnPropertyChanged(string name = null) {
if (this.PropertyChanged != null) {
PropertyChangedEventArgs ea = new PropertyChangedEventArgs(name);
this.PropertyChanged(this, ea);
}
}
}
Now when an item get removed or added to the collection, the model raises and PropertyChanged event so that the view will be aware that the IsDeleteOptionEnable property is (actually might) changed, and the enabled state of the button gets updated.
Try
IsEnabled="{Binding DataContext.IsDeleteOptionEnable, ElementName=LayoutRoot}"
As DataSource you need to use ObservableCollection. Then you need to implement INotifyPropertyChanged -interface in the class which contains the binded Property.
Example Class:
// Example of binded object
public class MyItem: INotifyPropertyChanged {
// Binded Property
private String itemIsVisible = "Yes";
public String ItemIsVisible{
get { return itemIsVisible; }
set {
itemIsVisible = value;
// This ensures the updating
OnPropertyChanged("ItemIsVisible");
}
}
protected void OnPropertyChanged(string name) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Example XAML:
<TextBlock Text="{Binding ItemIsVisible}" />
I have user control which has two controls
Label and TextBlock
<UserControl x:Class=MyClass....
d:DesignHeight="300" d:DesignWidth="300" x:Name="MyUsrCtrl">
<StackPanel>
<Label Content={Binding MyLabelContent} x:Name="MyLabel"...../>
<TextBlock Content={Binding MyTextBlockContent} x:Name="MyTextBlock"...../>
</StackPanel>
</UserControl>
and In my MainWindow I have a ListBox whose ItemSource is binded to collection of this usercontrol
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
<Grid>
<ListBox x:Name="myListBox" Grid.Row="0"
ItemsSource="{Binding Path=_myControl}"> // collection of user controls
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<local:MyUserControl x:Name="myUserControl" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
How can I get the value of the Textblock and Label when any item is selected in Listbox?
this worked for me:
Created a model called MyControl that "represents" the data in MyUserControl
Created an ObservableCollection That "represents" the data in the Listbox
This way you can also the delete all the x:Name
Seperates Data from UI
MainWindow.xaml
<ListBox x:Name="MyListBox" Grid.Row="0"
ItemsSource="{Binding MyControls}"
SelectionChanged="MyListBox_OnSelectionChanged"
SelectionMode="Single"
>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<local:MyUserControl></local:MyUserControl>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
MainWindow.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
MyControls = new ObservableCollection<MyControl>();
var a = new MyControl { MyLabelContent = "label content 1", MyTextBlockContent = "Text content 1" };
var b = new MyControl { MyLabelContent = "label content 2", MyTextBlockContent = "Text content 2" };
MyControls.Add(a);
MyControls.Add(b);
}
private void MyListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
if (listBox != null)
{
var selectedItem = listBox.SelectedItems[0] as MyControl;
var textBlockContent = selectedItem.MyTextBlockContent; //text in textblock
var labelContent = selectedItem.MyLabelContent; //text in label
}
}
private ObservableCollection<MyControl> _myControls;
public ObservableCollection<MyControl> MyControls
{
get { return _myControls; }
set
{
_myControls = value;
NotifyPropertyChanged("MyControls");
}
}
#region PropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
MyUserControl.XAML
<StackPanel>
<Label Content="{Binding MyLabelContent}" />
<TextBlock Text="{Binding MyTextBlockContent}" />
</StackPanel>
MyControl.cs
public class MyControl
{
public string MyLabelContent { get; set; }
public string MyTextBlockContent { get; set; }
}
Hopes this works for you :)
Here is a link to a working sample:
https://drive.google.com/file/d/0B8O-XH0V_o1hNXprX2c0S0xJUFU/view?usp=sharing
If you want to get TextBlock from selected item, you can do like this:
var selectedUserControl = myListBox.SelectedItem as MyUserControl;
TextBlock textBlock = selectedUserControl.MyTextBlock;
Hope helps!
I am new to MVVM and still trying to get a grasp on it so let me know if I'm setting this up wrong. What I have is a UserControl with a ListView in it. I populate this ListView with data from the ViewModel then add the control to my MainView. On my MainView I have a button that I want to use to add an item to the ListView. Here is what I have:
Model
public class Item
{
public string Name { get; set; }
public Item(string name)
{
Name = name;
}
}
ViewModel
public class ViewModel : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
private ObservableCollection<Item> _itemCollection;
public ViewModel()
{
ItemCollection = new ObservableCollection<Item>()
{
new Item("One"),
new Item("Two"),
new Item("Three"),
new Item("Four"),
new Item("Five"),
new Item("Six"),
new Item("Seven")
};
}
public ObservableCollection<Item> ItemCollection
{
get
{
return _itemCollection;
}
set
{
_itemCollection = value;
OnPropertyChanged("ItemCollection");
}
}
}
View (XAML)
<UserControl.Resources>
<DataTemplate x:Key="ItemTemplate">
<StackPanel Orientation="Vertical">
<Label Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<UserControl.DataContext>
<local:ViewModel />
</UserControl.DataContext>
<Grid>
<ListView ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemCollection}">
</ListView>
</Grid>
MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.mainContentControl.Content = new ListControl();
}
private void Button_Add(object sender, RoutedEventArgs e)
{
}
}
MainWindow (XAML)
<Grid>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<Button Width="100" Height="30" Content="Add" Click="Button_Add" />
</StackPanel>
<ContentControl x:Name="mainContentControl" />
</DockPanel>
</Grid>
Now, from what I understand, I should be able to just an item to ItemCollection and it will be updated in the view. How do I do this from the Button_Add event?
Again, if I'm doing this all wrong let me know and point me in the right direction. Thanks
You should not interact directly with the controls.
What you need to do is define a Command (a class that implements the ICommand-interface) and define this command on your ViewModel.
Then you bind the Button's command property to this property of the ViewModel. In the ViewModel you can then execute the command and add an item directly to your list (and thus the listview will get updated through the automatic databinding).
This link should provide more information:
http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx#sec11