I want to take a collection of objects and bind it to a StackPanel so basically if the collection has 4 elements, inside the stack panel that should produce 4 buttons lets say.
I tried this...But I dont think its the correct approach anyway. I used DataTemplated to do this type of idea in the past.. please correct me if I am wrong.
Here is my fake model
public class MockModel
{
public ObservableCollection<MockNode> Nodes;
public MockModel()
{
Nodes = new ObservableCollection<MockNode>();
}
}
public class MockNode
{
public MockNode()
{
}
private string itemname;
public string ItemName
{
get { return this.itemname; }
set { this.itemname = value; }
}
}
In code I set the DataContext like this...
// Init Model
MockModel myModel = new MockModel();
for (int i = 0; i < 4; i++)
{
MockNode mn = new MockNode();
mn.ItemName = String.Format("Node {0}", i);
myModel.Nodes.Add(mn);
}
// Set DataContext for StackPanel
Stack.DataContext = myModel.Nodes;
And the xaml
<StackPanel x:Name="tStack">
<ItemsControl ItemsSource="{Binding Nodes}">
<ItemsControl.Template>
<ControlTemplate>
<Button Content="{Binding ItemName}"/>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
</StackPanel>
IT does bind but instead of 4 buttons I only get one button....
Ideas?
Alright I have figured it out... Using an ItemsControl solved the problem...
<ItemsControl x:Name="tStack" ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding ItemName}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Related
This question already has answers here:
WPF 4 Drag and Drop with visual element as cursor
(2 answers)
Closed 1 year ago.
I have a list of items, which every item include a few of notes, like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Item> items = new List<Item>();
Item item1 = new Item() { Title = "First Item" };
Item item2 = new Item() { Title = "Second Item" };
item1.ItemNotes.Add(new ItemNote() { Note = "first_note" });
item1.ItemNotes.Add(new ItemNote() { Note = "second_note" });
item1.ItemNotes.Add(new ItemNote() { Note = "third_note" });
item2.ItemNotes.Add(new ItemNote() { Note = "fourth_note" });
item2.ItemNotes.Add(new ItemNote() { Note = "fifth_note" });
items.Add(item1);
items.Add(item2);
ic_tasks.ItemsSource = items;
}
}
public class Item
{
public Item()
{
this.ItemNotes = new ObservableCollection<ItemNote>();
}
public string Title { get; set; }
public ObservableCollection<ItemNote> ItemNotes { get; set; }
}
public class ItemNote
{
public string Note { get; set; }
}
In XAML I present those items by ItemsControl, like this:
<Grid>
<ItemsControl Name="ic_tasks">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Item}">
<StackPanel Orientation="Vertical">
<Border BorderThickness="1" CornerRadius="8" Background="DarkGray">
<StackPanel Orientation="Horizontal" Height="30">
<TextBox Text="{Binding Title}" Margin="5,5,5,5"/>
<Button Margin="5,5,5,5">Fold</Button>
</StackPanel>
</Border>
<ItemsControl ItemsSource="{Binding ItemNotes}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:ItemNote}">
<TextBox Margin="40,5,5,5" Text="{Binding Note}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
And now my goal is to make those Items moveable. For example, I would like to be able to move the second item over the first item, like below:
What I tried?
I try to wrap all ItemsControl by Canvas and bind position by Canvas.Top & Canvas.Left by using Mouse Events, but there's no such property for StackPanel which I want to move. There's only such propery for ItemsControl, like below:
<Canvas x:Name="canvas_of_items">
<ItemsControl Name="ic_tasks" Canvas.Top="{Binding YPosition}" Canvas.Left="{Binding XPosition}">
<...>
<StackPanel Orientation="Horizontal" Height="30" PreviewMouseDown="StackPanel_MouseDown" PreviewMouseMove="StackPanel_MouseMove" PreviewMouseUp="StackPanel_MouseUp">
<...>
</ItemsControl>
</Canvas>
So my question is:
What are the options to allow Items to be moved between themselves? Importantly, when moving the Item, it should be visible, not the mouse cursor itself.
You can set the ItemsControl to place your items in a canvas using ItemsControl.ItemsPanel like this:
<ItemsControl Name="ic_tasks">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas></Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
But to move the items you cant just set the Canvas properties on the StackPanel because they are surrounded by ContentPresenter. Instead you use ItemsControl.ItemContainerStyle to set a style on these ContentPresentors and there you can do something like this:
<Style>
<Setter Property="Canvas.Left" value="<<somthing - propebly a binding so it will be easy to change>>"
</Style>
I'm creating a WPF application using MVVM pattern (at least I'm trying). There is <TabControl> with bound ItemsSource,which is an ObservableCollection<TabModel> Tabs. Tabs has Name and Items property, where Items is a list of ControlModel, which means Controls. I have problem with binding IsEnabled property to Grid where Items are placed.
Below there is a part of my code presenting the way I'm doing this:
private ObservableCollection<TabModel> tabs;
public ObservableCollection<TabModel> Tabs
{
get
{
if (tabs == null)
{
tabs = new ObservableCollection<TabModel>();
RefreshTabs();
}
return tabs;
}
set
{
tabs = value;
OnPropertyChanged("Tabs");
}
}
\\Tab Model
public string Name { get; set; }
private List<ControlModel> items;
public List<ControlModel> Items
{
get { return items; }
set
{
items = value;
OnPropertyChanged("Items");
}
}
And xaml...
<TabControl Margin="0,100,0,0" ItemsSource="{Binding Tabs,UpdateSourceTrigger=PropertyChanged}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ScrollViewer VerticalScrollBarVisibility="Hidden">
<Grid Margin="5,5,5,5" IsEnabled="{Binding IsProductEditionEnabled}">
<!--<Grid Margin="5,5,5,5">-->
<ItemsControl ItemsSource="{Binding Items,UpdateSourceTrigger=PropertyChanged}" ItemTemplateSelector="{StaticResource ControlTemplateSelector}"/>
</Grid>
</ScrollViewer>
</DataTemplate>
</TabControl.ContentTemplate>
The part...
<Grid Margin="5,5,5,5" IsEnabled="{Binding IsProductEditionEnabled}">
is not working. There is no error. This grid is always disabled. By default it's false.
private bool isProductEditionEnabled = false;
public bool IsProductEditionEnabled
{
get { return isProductEditionEnabled; }
set
{
isProductEditionEnabled = value;
OnPropertyChanged("IsProductEditionEnabled");
}
}
The question is : How to bind IsEnabled in my case properly?
You are inside a DataTemplate so you need to specify where the parent DataContext is when you do the binding, something like this:
<DataTemplate>
<ScrollViewer VerticalScrollBarVisibility="Hidden">
<Grid IsEnabled="{Binding Path=DataContext.IsProductEditionEnabled,
RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}">
</Grid>
</ScrollViewer>
</DataTemplate>
I'm trying to use Caliburn.Micro to bind a view model of a nested ListBox but I'm stuck.
I have a list workspace that is divided in two sections a list of groups containtaining items in a different part of that workspace I want to show the details of either a group or an item in a group depending on what is the SelectedItem. I'm new to Caliburn.Micro and looked at the documentation and samples but don't know how to connect the dots. Specifically I'm trying to model this after the Caliburn.Micro.HelloScreens sample. The code I have so far:
The ViewModel:
public class AnalyzerGroupWorkspaceViewModel : Conductor<AnalyzerGroupWorkspaceViewModel>, IWorkspace
{
private Selected selected = Selected.AnalyzerGroup;
private const string name = "Analyzers";
public AnalyzerGroupWorkspaceViewModel(
IMappingEngine fromMapper,
IRepository<Model.AnalyzerGroup> analyzerGroups)
{
AnalyzerGroups = new ObservableCollection<IAnalyzerGroupViewModel>(analyzerGroups.GetAll().Select(fromMapper.Map<Model.AnalyzerGroup,AnalyzerGroupViewModel>));
}
public ObservableCollection<IAnalyzerGroupViewModel> AnalyzerGroups { get; private set; }
public string Name { get { return name; } }
public Selected Selected
{
get { return selected; }
set
{
if (value == selected) return;
selected = value;
NotifyOfPropertyChange(() => Selected);
}
}
private IConductor Conductor { get { return (IConductor) Parent; } }
public void Show()
{
var haveActive = Parent as IHaveActiveItem;
if (haveActive != null && haveActive.ActiveItem == this)
{
DisplayName = name;
Selected = Selected.AnalyzerGroup;
}
else
{
Conductor.ActivateItem(this);
}
}
}
The view:
<UserControl x:Class="Philips.HHDx.SSW.AnalyzerGroup.AnalyzerGroupWorkspaceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<DockPanel>
<GroupBox Header="AnalyzerGroups" DockPanel.Dock="Top">
<ListBox x:Name="AnalyzerGroups">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" />
<ListBox x:Name="Analyzers">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Id }"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</GroupBox>
<GroupBox Header="Details">
<ContentControl cal:View.Context="{Binding Selected, Mode=TwoWay}"
cal:View.Model="{Binding}"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Stretch"/>
</GroupBox>
</DockPanel>
</UserControl>
Next to that I have two UserControls that display the detailsof a group or item.
My specific question is how can I use the SelectedItem property of the two ListBoxes to modify the Selected property to switch between displaying the AnalyzerGroup details and the Analyzer details?
I've found the solution to the above described problem the solution consists of four parts:
Add a IsSelected property (that notifies changes) to both 'child' ViewModels
Bind the IsSelected property of the ListBox.ItemContainerStyle to the IsSelected property of the respective ViewModels
Attach a Caliburn.Micro Message to the 'outer' ListBox and use the $eventArgs argument
In the ViewModel bound to the entire UserControl implement the method corresponding to the Message and use the AddedItems property of the eventArgs to set the SelectedViewModel property setting the IsSelected property of the previous SelectedViewModel to false
The code then becomes:
The ViewModel:
public class AnalyzerGroupWorkspaceViewModel : PropertyChangedBase, IAnalyzerGroupWorkspaceViewModel
{
private IAnalyzerViewModel selectedViewModel;
private const string WorkspaceName = "Analyzers";
public AnalyzerGroupWorkspaceViewModel(
IMappingEngine fromMapper,
IRepository<Model.AnalyzerGroup> analyzerGroups)
{
AnalyzerGroups = new ObservableCollection<IAnalyzerGroupViewModel>(
analyzerGroups.GetAll().Select(
fromMapper.Map<Model.AnalyzerGroup, AnalyzerGroupViewModel>));
}
public void SelectionChanged(object eventArgs)
{
var typedEventArgs = eventArgs as SelectionChangedEventArgs;
if (typedEventArgs != null)
{
if (typedEventArgs.AddedItems.Count > 0)
{
var item = typedEventArgs.AddedItems[0];
var itemAsGroup = item as IAnalyzerViewModel;
if (itemAsGroup != null)
{
SelectedViewModel = itemAsGroup;
}
}
}
}
public ObservableCollection<IAnalyzerGroupViewModel> AnalyzerGroups { get; private set; }
public string Name { get { return WorkspaceName; } }
public IAnalyzerViewModel SelectedViewModel
{
get { return selectedViewModel; }
set
{
if (Equals(value, selectedViewModel))
{
return;
}
if (SelectedViewModel != null)
{
SelectedViewModel.IsSelected = false;
}
selectedViewModel = value;
NotifyOfPropertyChange(() => SelectedViewModel);
}
}
}
The View:
<UserControl x:Class="Philips.HHDx.SSW.AnalyzerGroup.AnalyzerGroupWorkspaceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<DockPanel>
<GroupBox Header="AnalyzerGroups" DockPanel.Dock="Top">
<ListBox SelectionMode="Single"
x:Name="AnalyzerGroups"
cal:Message.Attach="[Event SelectionChanged] = [Action SelectionChanged($eventArgs)]">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="2" BorderBrush="DarkGray">
<StackPanel Orientation="Vertical" Margin="10">
<TextBlock Text="{Binding Name}" />
<ListBox SelectionMode="Single" ItemsSource="{Binding Analyzers}" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="DarkGray">
<StackPanel>
<TextBlock Text="{Binding Name }" Margin="10" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</GroupBox>
<GroupBox Header="Details">
<ContentControl cal:View.Model="{Binding SelectedViewModel}" />
</GroupBox>
</DockPanel>
</UserControl>
The answer to your specific question is yes, you can.
On the ViewModel of your UserControl. You create a property that is a ViewModel of either of the two details.
public interface IAnalyzerViewModel
{
}
Next, create two ViewModels for the Views of your Analyzer and AnalyzerGroup views.
public class AnalyzerGroupViewModel : IAnalyzerViewModel
{
}
public class AnalyzerViewModel : IAnalyzerViewModel
{
}
Next, create a property in your UserControl's ViewModel that implements INPC or PropertyChangedBase of Caliburn Micro.
public class MainViewModel :
{
private IAnalyzerViewModel _analyzerViewModel;
public IAnalyzerViewModel SelectedViewModel { get { return _analyzerViewModel; } set { _analyzerViewModel = value; OnPropertyChanged(() => SelectedViewModel); }
//Hook up the selected item changed event of your listbox and set the appropriate ViewModel to show, so if you either want to show the AnalyzerGroup or AnalyzerView.
}
And lastly, just update your MainView to
<ContentControl x:Name="SelectedViewModel"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Stretch"/>
Caliburn will hook up the appropriate bindings and stuff and will pull the View for the associated ViewModel, and also the Name convention part will automatically map it to any public property of its datacontext as long as the names match.
So, I have already posted a question about the nested controls structure in WPF, it is here:
Nested controls structure - in XAML or C#?
And I have received a solution as follows:
<ItemsControl ItemsSource="{Binding SomeCollectionOfViewModel}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding SomeCollection}"> <!-- Nested Content -->
...
</DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
I have used that solution, comming up with this:
<!-- The UniformGrids - boxes -->
<ItemsControl ItemsSource="{Binding UniformGridCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- The TextBoxes - Cells -->
<ItemsControl ItemsSource="{Binding TextBoxCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Here is the C# side:
public partial class MainWindow : Window
{
private readonly ObservableCollection<UniformGrid> uniformGridCollection = new ObservableCollection<UniformGrid>();
public ObservableCollection<UniformGrid> UniformGridCollection { get { return uniformGridCollection; } }
private readonly ObservableCollection<UniformGrid> textBoxCollection = new ObservableCollection<UniformGrid>();
public ObservableCollection<UniformGrid> TextBoxCollection { get { return textBoxCollection; } }
public MainWindow()
{
InitializeComponent();
for (int i = 1; i <= 9; i++)
{
UniformGrid box = new UniformGrid();
UniformGridCollection.Add(box);
UniformGrid cell = new UniformGrid();
TextBoxCollection.Add(cell);
}
DataContext = this;
}
}
But somehow the "Cells" - textboxes, that are inside the uniformgrids, do not create. Instead, I get only 9 uniform grids contain in one big uniform Grid (specified in Paneltemplate).
I have checked the prgram with Snoop v 2.8.0:
http://i40.tinypic.com/htzo5l.jpg
The question is: Could somebody tell me, why the inside structure(textboxes) arent created?
You're not defining any TextBoxes anywhere, That's why you're not getting any TextBoxes in the Visual Tree:
<Window x:Class="MiscSamples.NestedItemsControls"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="NestedItemsControls" Height="300" Width="300">
<ItemsControl ItemsSource="{Binding Level1}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Level2}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Value}"/> <!-- You Are missing this! -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
Also, as mentioned in the comment, your Collections should be of ViewModel or Model types, not UI types:
ViewModels:
public class NestedItemsViewModel
{
public List<Level1Item> Level1 { get; set; }
}
public class Level1Item
{
public List<Level2Item> Level2 { get; set; }
}
public class Level2Item
{
public string Value { get; set; }
}
Code Behind:
public partial class NestedItemsControls : Window
{
public NestedItemsControls()
{
InitializeComponent();
DataContext = new NestedItemsViewModel()
{
Level1 = Enumerable.Range(0, 10)
.Select(l1 => new Level1Item()
{
Level2 = Enumerable.Range(0, 10)
.Select(l2 => new Level2Item { Value = l1.ToString() + "-" + l2.ToString() })
.ToList()
})
.ToList()
};
}
}
Notice that you will have to change the Lists to ObservableCollections if you expect these collections to change dynamically during runtime.
Also notice you have to implement INotifyPropertyChanged properly.
I can't get the simplest idea of an ItemControl to work. I just want to populate my ItemsControl with a bunch of SomeItem.
This is the code-behind:
using System.Collections.ObjectModel;
using System.Windows;
namespace Hax
{
public partial class MainWindow : Window
{
public class SomeItem
{
public string Text { get; set; }
public SomeItem(string text)
{
Text = text;
}
}
public ObservableCollection<SomeItem> Participants
{ get { return m_Participants; } set { m_Participants = value; } }
private ObservableCollection<SomeItem> m_Participants
= new ObservableCollection<SomeItem>();
public MainWindow()
{
InitializeComponent();
Participants.Add(new SomeItem("Hej!"));
Participants.Add(new SomeItem("Tjenare"));
}
}
}
This is the XAML:
<ItemsControl Name="itemsParticipants"
ItemsSource="{Binding Path=Participants}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="2">
<TextBlock Text="{Binding Text}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
What am I doing wrong?
Make sure your datacontext is set to RelativeSource Self somewhere in your xaml. If you could post more of your xaml it might be helpful.
<ItemsControl... DataContext="{Binding RelativeSource={RelativeSource Self}}" >
The ItemsSource references a property called MyParticipants, whereas the code it looks to be Participants.
Check the Debug Output view, and you should see error messages.