I don't know if my understanding of binding is just poor or if I am not seeing the problem, but I hope someone can help me out here. I have a ListView with a template of an image and a TextBlock, I need the TextBlock to be bound to the ItemsSource of the ListView. However when I run this I get nothing shown, I don't even see my image that I have set.
XAML:
<UserControl.Resources>
<FontFamily x:Key="FontFamily">MS Reference Sans Serif</FontFamily>
</UserControl.Resources>
<Grid>
<ListView BorderThickness="0" ItemsSource="{Binding Facies}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="../Images/Shale.png"/>
<TextBlock Text="{Binding FaciesName}" Width="75" Margin="5"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
C#:
public partial class FaciesControl : UserControl
{
public FaciesControl()
{
InitializeComponent();
}
public List<string> Facies {get; set;}
public void Bind(string[] data)
{
Facies = new List<string>();
Facies.AddRange(data);
}
}
First set DataContext like this:
public FaciesControl()
{
InitializeComponent();
string[] str = { "Name1", "Name2", "Name3" };
Bind(str); // Make sure you have called the Bind method
DataContext = Facies;
}
Second change your XAML like this:
<ListView BorderThickness="0" ItemsSource="{Binding}">
....
....
<TextBlock Text="{Binding}" Width="75" Margin="5"/>
Related
I have a ListView. I need to add ListViewItems programatically that contain a Textblock nested inside of a StackPanel, nested inside of a Grid (For the purpose of formatting the text). I am relatively new to WPF and I cannot find an answer. Here is the code that I would like each ListViewItem to have once added:
<ListViewItem Padding="15">
<Grid Width="1285">
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Width="Auto">
<TextBlock Text="ITEM" VerticalAlignment="Center" />
</StackPanel>
</Grid>
</ListViewItem>
Here is an image to demonstrate what I am trying to do.The code above puts the ListViewItem in the middle, but by using a Grid and a StackPanel, I was able to center the text (StackPanel was actually for the purpose of adding an icon alongside it but I've temporarily taken that out. If someone knows how to do this better then by all means tell me.
So, what you need is a UserControl, which will be used to display each item in your ListView. So you must design your user control the way you want it to look; so if you need a TextBlock inside a panel inside a grid, that's what you must do.
<UserControl x:Class="SOWPF.MyListViewItem"
....
mc:Ignorable="d"
d:DesignHeight="48" d:DesignWidth="250">
<Grid>
<StackPanel Orientation="Horizontal" Width="250" Height="36" Margin="10" Background="PeachPuff">
<TextBlock Background="White" Width="200" Height="32" Margin="2" Text="{Binding DisplayText}"/>
</StackPanel>
</Grid>
</UserControl>
To display data, you must have a class with public properties. So I have this simple class with one public string property, which will contain the text you want to display in the TextBlock. The data binding on the user control refers to this; DisplayText is the public string property:
public class DisplayData
{
public string DisplayText { get; set; }
}
Now in your View, you must use a ContentControl inside your ListView to display your UserControl dynamically.
<Window x:Class="SOWPF.MainWindow"
....
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ListView>
<ItemsControl ItemsSource="{Binding DisplayList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:MyListViewItem/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ListView>
</Grid>
</Window>
And here's your code behind. I did it this way for convenience, but you really should use a ViewModel.
public partial class MainWindow : Window
{
public List<DisplayData> DisplayList { get; set; }
public MainWindow()
{
InitializeComponent();
DisplayList = new List<DisplayData>
{
new DisplayData() { DisplayText = "A" },
new DisplayData() { DisplayText = "B" },
new DisplayData() { DisplayText = "C" }
};
DataContext = this;
}
}
Result:
EDIT (After OP edited the question)
If all you want to do is center text, you can get rid of extra controls and simply use TextAlignment=Center in your TextBlock.
<UserControl x:Class="SOWPF.MyListViewItem"
....
mc:Ignorable="d"
d:DesignHeight="48" d:DesignWidth="250">
<TextBlock Background="LightCoral" Width="200" Height="32" Margin="2" Text="{Binding DisplayText}"
TextAlignment="Center"/>
</UserControl>
And it'll look like this:
Alrighty, so I have, as I said, a ComboBox within a ListBox. These are both controls (WPF project using C# in Visual Studio 2010 and MVVM).
I can create them all good and well.
The ListBox contains an ObservableCollection of something called IntWrapper, which just contains and int.
The ComboBox is loaded with an ObservableCollection of something called MissionViewModel, which is just a class that contains a few basic data types.
So the ItemSource for the ListBox and the ComboBox are different.
I can add and items to the ListBox with a button, which just adds a new IntWrapper to the ObservableCollection. Visually this gives me a new ComboBox, which is populated.
What I can't figure out is how to get one of the properties of MissionViewModel to go to the property in the IntWrapper when I select it.
Previously I just used a TextBox in the ListBox, which looked like this:
<ListBox x:Name="lbMissionsToGive" ItemsSource="{Binding MissionsToGive}" SelectedItem="{Binding SelectedMissionToGive}" ContextMenu="{StaticResource RemoveMissionToGiveMenu}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="2" BorderBrush="LightBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2" CornerRadius="5,5,5,5">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="1">Mission ID: </TextBlock>
<TextBox Margin="1" Text="{Binding Int, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My (non working) attempt whereby I replace the TextBox with the ComboBox is this:
<ListBox x:Name="lbMissionsToGive" ItemsSource="{Binding MissionsToGive}" SelectedItem="{Binding SelectedMissionToGive}" ContextMenu="{StaticResource RemoveMissionToGiveMenu}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="2" BorderBrush="LightBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2" CornerRadius="5,5,5,5">
<StackPanel Orientation="Horizontal">
<ComboBox DisplayMemberPath="MissionNameAndID" SelectedValuePath="Int" ItemsSource="{Binding MissionListViewModel.MissionVMs, Source={StaticResource Locator}}"></ComboBox>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I had thought SelectedValuePath would be the thing I wanted, but this so far doesn't seem to work (perhaps I'm using it incorrectly).
Any assistance would be appreciated.
Bind the SelectedValue property of the ComboBox to the Int property of the IntWrapper:
<ComboBox DisplayMemberPath="MissionNameAndID" SelectedValuePath="Int" SelectedValue="{Binding Int}"
ItemsSource="{Binding MissionListViewModel.MissionVMs, Source={StaticResource Locator}}" />
This should work provided that the IntWrapper.Int property has a public setter and that the Int property of the MissionViewModel is of the same type as the Int property of the IntWrapper.
I tried to create a solution for your problem based on your description. To help you more qualified, we would need more information about the MissionViewModel and the Properties contained in it.
I suppose, your Binding does not point to the correct ViewModel. I tried to recreate what you describe below and in my case, the combobox is filled with the Name Property of the MissionVm class.
This is the XAML. Here I changed the ItemsSource Binding to directly point to the ObservableCollection of the DataContext of the parent window.
<ListBox x:Name="lbMissionsToGive" ItemsSource="{Binding MissionsToGive}" SelectedItem="{Binding SelectedMissionToGive}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="2" BorderBrush="LightBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2" CornerRadius="5,5,5,5">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding }"></TextBlock>
<ComboBox Margin="20" Width="50" ItemsSource="{Binding DataContext.MissionVMs, RelativeSource={RelativeSource AncestorType=Window}}" DisplayMemberPath="Name"></ComboBox>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And this is the ViewModel based on your description:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
var vm1 = new MissionVM { Id = 1, Name = "111"};
var vm2 = new MissionVM { Id = 2, Name = "222" };
var vm3 = new MissionVM { Id = 3, Name = "333" };
MissionVMs = new ObservableCollection<MissionVM> { vm1, vm2, vm3};
MissionsToGive = new ObservableCollection<int> {1, 2, 3};
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ObservableCollection<int> MissionsToGive { get; set; }
public int SelectedMissionToGive { get; set; }
public ObservableCollection<MissionVM> MissionVMs { get; set; }
}
public class MissionVM
{
public int Id { get; set; }
public string Name { get; set; }
}
This is the Output:
I hope this helps. If i misunderstood you, please give further explanation of the problem.
Here's my problem:
I've got these classes:
public class CsvField
{
public string Content { get; set; }
public CsvField(string content)
{
Content = content;
}
}
public class CsvLine
{
public List<CsvField> Fields = new List<CsvField>();
public int LineNumber;
}
public static class Settings
{
public static List<string> Tags = new List<string>();
public static CsvLine AllHeaders = new CsvLine();
}
What I want to do, is display the ListBox containing every member of Settings.AllHeaders.Fields and a ComboBox containing all members of Settings.Tags list (placed horizontally - a member of AllHeaders on the left and a ComboBox next to it). So if I had 4 headers, I would get a List of those 4 headers and 4 ComboBoxes, each of them next to individual header. Each of these ComboBoxes would contain a list of tags.
So, I defined a DataTemplate:
<Window x:Class="CSV_To_Tags_App.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:CSV_To_Tags_App"
Title="Window2" Height="435" Width="566">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:CsvField}">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="HeaderTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap"
VerticalAlignment="Top" Text="{Binding Content}"
/>
<ComboBox HorizontalAlignment="Right" VerticalAlignment="Top" Width="120"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<Label Content="Available headers" HorizontalAlignment="Left"
VerticalAlignment="Top"/>
<ListBox x:Name="HeadersListtListBox" HorizontalAlignment="Left"
Height="254" Margin="36,104,0,0" VerticalAlignment="Top" Width="452"
ItemsSource="{Binding}"/>
</Grid>
</Window>
Now, XAML code above is incomplete, because I don't know how to:
1. Bind TextBlock to Settings.AllHeaders.Fields.Content
2. Bind ComboBox to Tags List
The link provided by #MD's does provide the solution to what you are asking in your question, but you have to rearrange things a little bit to see it.
The XAML below will give you what you are asking for, assuming your class that you are binding to is set up properly for data binding (implementing the INotifyPropertyChanged interface). There are lots of examples on this site of how to properly implement that portion.
<Window x:Class="CSV_To_Tags_App.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:CSV_To_Tags_App"
Title="Window2" Height="435" Width="566">
<Grid>
<StackPanel Orientation="Horizontal">
<ItemsControl ItemsSource="{Binding Path=Settings.AllHeadings.Fields}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Content}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Path=Settings}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=Tags}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</Window>
I have an ObservableCollection of a class (TopLevel) that contains a name property and a list of another ObservableCollection of class (BottomLevel) that has just a name property. The binding on the highest list works, but when I try to bind to the property on the BottomList I get nothing. What am I missing here?
XAML:
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="myGrid" DataContext="topList">
<Border BorderBrush="AliceBlue" Grid.Column="0" BorderThickness="5">
<ItemsControl x:Name="ic1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=TopName}"/>
<Border BorderBrush="AntiqueWhite" Grid.Column="1" BorderThickness="5">
<Button Content="{Binding Path=BottomList.BottomName}"/>
</Border>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</Grid>
Code behind:
public partial class MainWindow : Window
{
public ObservableCollection<TopLevel> topList;
public MainWindow()
{
InitializeComponent();
topList = new ObservableCollection<TopLevel>();
topList.Add(new TopLevel("T" + (1 + topList.Count).ToString()));
topList[0].AddBottom();
topList.Add(new TopLevel("T" + (1 + topList.Count).ToString()));
topList[1].AddBottom();
ic1.ItemsSource = topList;
}
}
public class TopLevel
{
private ObservableCollection<BottomLevel> bottomList;
private string topName;
public void AddBottom()
{
bottomList.Add(new BottomLevel("B" + (1 + bottomList.Count).ToString()));
}
public TopLevel(string x)
{
bottomList = new ObservableCollection<BottomLevel>();
topName = x;
}
public string TopName
{
get
{
return topName;
}
set
{
if (topName!=value)
{
topName = value;
}
}
}
public ObservableCollection<BottomLevel> BottomList
{
get
{
return bottomList;
}
set
{
if (bottomList!=value)
{
bottomList = value;
}
}
}
}
public class BottomLevel
{
private string bottomName;
public BottomLevel(string x)
{
bottomName = x;
}
public string BottomName
{
get
{
return bottomName;
}
set
{
if (bottomName!=value)
{
bottomName = value;
}
}
}
}
Your path for the button is incorrect. BottomList does not have a "Name" property, so you can't bind to it. Instead, just use BottomName as your path.
Since your topList has a collection of "BottomLevel" you'll need some sort of nested items control to iterate over the "bottomList" collection (then use "BottomName" for your path as above).
As it stands, you basically have:
<ItemsControl //List of TopLevel>
//Your data context is now the TopLevel item itself
<Button Path=/> //What goes here? you have a whole collection of BottomLevel items to choose from!
</ItemsControl>
If you have only one item in BottomList Then you can use the below code for Button
<Button Content="{Binding Path=BottomList[0].BottomName}" Height="50"/>
If you want to Bind the BottomList to some List Control you can bind to the DataGrid then you can use the below code.
<Grid x:Name="myGrid" DataContext="topList">
<Border BorderBrush="AliceBlue" Grid.Column="0" BorderThickness="5">
<ItemsControl x:Name="ic1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=TopName}"/>
<Border BorderBrush="AntiqueWhite" Grid.Column="1" BorderThickness="5">
<DataGrid ItemsSource="{Binding Path=BottomList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Path=BottomName}" Height="50"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Border>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</Grid>
Please let me know if you need any more help.
Hello I'm trying to dynamically change datatemplate but my method SelectTemplate in class TreeViewItemTemplateSelector never getting called (I've checked it by debugger) :( please help me :)
Code from xaml MainWindow:
Code in code behind:
Your problem seems to be that your TreeViewCustomItem is inheriting from TreeViewItem. (As seen in http://pastebin.com/jnP2nWMF)
Removing that inheritance (and the dependency property) causes the template selector to fire fine. What were/are you trying to achieve with the node item?
Looking at the OutputWindow, I get this message:
System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='TreeViewCustomItem'
You don't have to have items inherit from the TreeViewItem in order to bind them to a TreeView, TreeViewItem is something that the TreeView uses to hold the data, and then the DataTemplate is used to present the data.
Move DataTemplates from TreeView.Resources to Window.Resources
<Window.Resources><DataTemplate x:Key="DefaultTemplate">
<TextBlock Text="{Binding Header}"></TextBlock>
</DataTemplate><DataTemplate x:Key="Regulation">
<TextBlock Text="{Binding Path=Header}" FontWeight="Bold"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="Article">
<TextBlock Text="{Binding Path=Header}" Foreground="Green"></TextBlock>
</DataTemplate>
<local:TreeViewItemTemplateSelector x:Key="TemplateSelector" DefaultTemplate="{StaticResource DefaultTemplate}" ArticleTemplate="{StaticResource Article}" RegulationTemplate="{StaticResource Regulation}" />
and make change
<TreeView ItemTemplateSelector="{StaticResource TemplateSelector}" Height="409" HorizontalAlignment="Left" Margin="10,10,0,0" Name="treeView1" VerticalAlignment="Top" Width="277" ItemsSource="{Binding}"/>
Update code and we will see. I put similar code into VS and it works so we need to take a closer look. So i checked this and changed
public class TreeViewCustomItem
{
public string Header { get; set; }
}
and this
listmy = new ObservableCollection<TreeViewCustomItem> { new TreeViewCustomItem { Header = "xD" }, new TreeViewCustomItem { Header = "xxD" } };
//treeView1.ItemsSource = listmy;
this.DataContext = listmy;
public class selector : DataTemplateSelector
{
public DataTemplate RegulationTemplate { get; set; }
public DataTemplate DefaultTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
TreeViewCustomItem treeViewItem = item as TreeViewCustomItem;
if (treeViewItem.Header == "xD")
{
return RegulationTemplate;
}
else
{
return DefaultTemplate;
}
}
}
and in XAML looks like this
xmlns:local="clr-namespace:WpfApplication1.Views">
<Window.Resources>
<DataTemplate x:Key="DefaultTemplate">
<TextBlock Text="{Binding Header}"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="Regulation">
<TextBlock Text="{Binding Path=Header}" FontWeight="Bold"></TextBlock>
</DataTemplate>
<local:selector x:Key="selector_" DefaultTemplate="{StaticResource DefaultTemplate}" RegulationTemplate="{StaticResource Regulation}"/>
</Window.Resources>
<Grid>
<TreeView Height="409" HorizontalAlignment="Left" Margin="10,10,0,0" Name="treeView1" VerticalAlignment="Top" Width="277"
ItemsSource="{Binding}" ItemTemplateSelector="{StaticResource selector_}"/>
</Grid>
And it works so my presumption is that problem is inside TreeViewCustomItem.