Create ItemTemplate for ListBox in code-beind in WPF - c#

I'm trying to create an ItemTemplate for a ListBox programmatically but it doesn't work. I know in XAML I can have something like:
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But when I'm trying to have the above result programmatically I face a problem which is binding the TextBox.TextProperty:
var textblock = new FrameworkElementFactory(typeof(TextBlock));
// Setting some properties
textblock.SetValue(TextBlock.TextProperty, ??);
var template = new ControlTemplate(typeof(ListBoxItem));
template.VisualTree = textblock;
Please help me on this issue. I couldn't find anything on the web about it.
Thanks in advance.

Try use dot . in Binding, this is the equivalent of {Binding}.
Example:
XAML
<Window x:Class="MyNamespace.MainWindow"
...
Loaded="Window_Loaded">
<ListBox Name="MyListBox" ... />
</Window>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);
var template = new DataTemplate();
template.VisualTree = textBlockFactory;
MyListBox.ItemTemplate = template;
}
}

Try this, by binding the "listbox" with ItemsSource and specify the datatemplate below like if you want to bind name then just write {Binding Name}
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Related

Display database to listbox

I have a listbox containing a choice of text answers taken from the database and containing html languages, such as: <p>, etc. I want to display it so that the html language is not displayed. I tried to display it in the webview, but <p>, etc. is still visible.
XAML:
<ListBox Name="ListOption" Grid.Row="1" Margin="10,20,10,0" Height="auto" xmlns:m="using:KipinSchool_Win10.TryoutData.Models" SelectionChanged="ListAlternatives_SelectionChanged" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="m:DBOption">
<StackPanel Orientation="Horizontal">
<WebView Margin="10,10,10,10" local:MyProperties.HtmlString="{Binding Option}" MinHeight="40" MaxHeight="300" HorizontalAlignment="Stretch" Tag="{Binding OID}"/>
<TextBlock Text="{Binding Option}" Tag="{Binding OID}" FontSize="19"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code:
string strA = #"SELECT DISTINCT* FROM DBOption WHERE QID='" + question[0] + "'";
var alternative = objConn.Prepare(strA);
ObservableCollection<DBOption> Items = new ObservableCollection<DBOption>();
int i = 0;
while (alternative.Step() == SQLiteResult.ROW)
{
Items.Add(new DBOption(alternative[0].ToString(), alternative[1].ToString(), alternative[2].ToString(), alternative[3].ToString()));
}
Binding myBinding = new Binding();
myBinding.Source = Items;
ListOption.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
How to handle it?
I tried to display it in the webview, but etc. is still visible. XAML:
I could reproduce your issue, the problem is that you have not set width and height property for WebView. And html string does not contain the content height. So the WebView will not display correctly. Please modify the code like the following.
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<WebView Margin="10,10,10,10"
local:MyProperties.HtmlString="{Binding Option}"
Height="400" Width="200"
HorizontalAlignment="Stretch"
Tag="{Binding OID}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>

How to get the destination ListView item on drop?

In UWP C#, I have one ListView in upper row & another in lower row. When I drag a listitem from upper ListView & drop it on lower ListView, I am getting the source. But, I am unable to get the destination. ie) the listview item/(Folder object in my case) where I dropped.
<ListView Name="ListviewCars"
CanDragItems="True" DragItemsStarting="ListviewCars_DragItemsStarting"
SelectionMode="Single" IsItemClickEnabled="True"
DataContext="Cars" ItemsSource="{Binding CarsCollection}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="Transparent" Height="80" Orientation="Horizontal"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate >
<DataTemplate>
<Grid Name="GrdCars" >
<Grid Height="80" Width="90" Padding="5">
<Grid.Background>
<ImageBrush Stretch="Uniform" ImageSource="Assets/car.png"/>
</Grid.Background>
<TextBlock Text="{Binding Name}" FontWeight="Bold" TextWrapping="Wrap" TextAlignment="Center"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ListView Name="GrdViewImg" ScrollViewer.VerticalScrollBarVisibility="Disabled"
AllowDrop="True" DragOver="Image_DragOver"
Drop="Image_OnDrop"
DataContext="Folders" ItemsSource="{Binding FolderCollection}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="Transparent" Height="80" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate >
<DataTemplate>
<Grid Name="GrdForFolderMenu" RightTapped="GrdForFolderMenu_RightTapped">
<Grid Height="80" Width="90" Padding="5">
<Grid.Background>
<ImageBrush Stretch="UniformToFill" ImageSource="Assets/Folderimage.png"/>
</Grid.Background>
<TextBlock Text="{Binding Name}" FontWeight="Bold" TextWrapping="Wrap" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I have found a simple solution myself. I get the source from DragItemsStarting event of the SoureListView. and target item (as mentioned by ashchuk) from a Grid placed inside Datatemplate of Target ListView. as shown below. Everything works fine now!
(Cars is my Source custom list item. Folders is my Target custom list item)
private void SoureListView_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
Cars x = e.Items[0] as Cars;
string DraggedSourceCar = x.Name;
e.Data.Properties.Add("myArgs", DraggedSourceCar);
}
private void GridInsideDatatemplateOfTargetListview_Drop(object sender, DragEventArgs e)
{
var x = sender as Grid;
var y = x.DataContext as Folders;
string toMoveFolderName = y.Name;
string DraggedSourceCar = e.DataView.Properties["myArgs"].ToString();
Debug.WriteLine(DraggedSourceCar + Environment.NewLine + toMoveFolderName );
}
private void TargetListview_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
You have to find out by yourself = DragEventArgs.GetPosition() in the destination drop, then the underlying item with smoe helper functions
public static object GetObjectAtPoint<ItemContainer>(this ItemsControl control, Point p)
where ItemContainer : DependencyObject
{
// ItemContainer - can be ListViewItem, or TreeViewItem and so on(depends on control)
ItemContainer obj = GetContainerAtPoint<ItemContainer>(control, p);
if (obj == null)
return null;
return control.ItemContainerGenerator.ItemFromContainer(obj);
}
public static ItemContainer GetContainerAtPoint<ItemContainer>(this ItemsControl control, Point p)
where ItemContainer : DependencyObject
{
HitTestResult result = VisualTreeHelper.HitTest(control, p);
if (result != null)
{
DependencyObject obj = result.VisualHit;
while (VisualTreeHelper.GetParent(obj) != null && !(obj is ItemContainer))
{
obj = VisualTreeHelper.GetParent(obj);
}
// Will return null if not found
return obj as ItemContainer;
}
else return null;
}
Did you checked this sample?
After some research I found what DragEventArgs contains an OriginalSource property with Name matches the name of target list when Drop event invoked.
I'm not checked it with folders and subfolders, but maybe OriginalSource will contain folder where item dropped.
<TextBlock Grid.Row="1" Margin="8,4"
VerticalAlignment="Bottom"
Text="All Items"/>
<ListView x:Name="SourceListView"
Grid.Row="2" Margin="8,4"
SelectionMode="Extended"
CanDragItems="True"
DragItemsStarting="SourceListView_DragItemsStarting"/>
<TextBlock Grid.Row="1" Grid.Column="1" Margin="8,4"
VerticalAlignment="Bottom"
Text="Selection"/>
<ListView x:Name="TargetListView"
Grid.Row="2" Grid.Column="1" Margin="8,4"
AllowDrop="True" CanReorderItems="True" CanDragItems="True"
DragOver="TargetListView_DragOver"
Drop="TargetListView_Drop"
DragItemsStarting="TargetListView_DragItemsStarting"
DragItemsCompleted="TargetListView_DragItemsCompleted"/>
And here is printscreen with fired breakpoint:
EDIT:
To get an item inside of TargetList you can do a trick.
I think you use DataTemplate to display custom list items ("folders"). You can see a sample below. As you see I add Grid_DragOver trigger.
<Page.Resources>
<DataTemplate x:Key="ListViewDataTemplate">
<Grid Margin="20,5" DragOver="Grid_DragOver"
BorderBrush="White" BorderThickness="5" AllowDrop="True">
<TextBlock Margin="10" LineHeight="40" FontSize="32" FontWeight="Bold"/>
</Grid>
</DataTemplate>
</Page.Resources>
This way Grid_DragOver will be invoked when mouse pointer enter inside the Grid in DataTemplate.
And if you use binding List<YourFolderClass> as data source, you'll get folder in DataContext. For example I used this:
var SampleData = new ObservableCollection<string>
{
"My Research Paper",
"Electricity Bill",
"My To-do list",
"TV sales receipt",
"Water Bill",
"Grocery List",
"Superbowl schedule",
"World Cup E-ticket"
};
You can see all code in gist.

Combo box add item from template

Im trying to add items to the combo box from the code behind to the item template but im getting null. This is what I have so far:
XAML:
<ListBox x:Name="lsbCiertoYFalsoInsideTemplate" Margin="40,0,0,0" ItemTemplate="{StaticResource CiertoYFalsoExcerciseDataTemplate}"/>
App.xaml:
<DataTemplate x:Key="CiertoYFalsoExcerciseDataTemplate">
<Grid>
<StackPanel x:Name="stckCiertoYFalsoInsideTemplate" Margin="0" Orientation="Vertical" Width="1100">
<StackPanel x:Name="stckPreguntasCiertoYFalso" Orientation="Horizontal">
<Grid Height="50" Width="65" DataContext="{Binding CustomValueList}" VerticalAlignment="Top">
<ComboBox x:Name="cbExercises" Style="{StaticResource SA_ComboBoxStyle}" ItemsSource="{Binding CustomOption}" BorderBrush="#CC8C8C8C" VerticalAlignment="Top">
</ComboBox>
</Grid>
<TextBlock HorizontalAlignment="Center" Margin="5,3,0,0" TextWrapping="Wrap" Text="{Binding QuestionNumber}" VerticalAlignment="Top" FontWeight="Bold" Foreground="Black" Width="26" FontFamily="{Binding FontFamily, Source={StaticResource TextBlockStyleManager}}" FontSize="{Binding FontSize, Source={StaticResource TextBlockStyleManager}}"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Question}" Foreground="Black" VerticalAlignment="Top" FontSize="{Binding FontSize, Source={StaticResource TextBlockStyleManager}}" Margin="10,3,0,0" Width="968" FontFamily="{Binding FontFamily, Source={StaticResource TextBlockStyleManager}}"/>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
The error im getting is object out of range.
Code:
private void ComboBoxExercises()
{
ComboBox comboBox = new ComboBox();
ComboboxItem item = new ComboboxItem();
item.Text = "A";
comboBox = (ComboBox)lsbCiertoYFalsoInsideTemplate.FindName("cbExercises");
comboBox.SelectedIndex = 0;
comboBox.Items.Add(item);
}
public class ComboboxItem
{
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
There's a disconnect in what you're trying to do here. You've specified an ItemTemplate - which defines how each item in the list will look.
But then you're trying to get one single ComboBox back out via the FindName function. Which leads me to believe that you're really intending to set the Template, not the ItemTemplate.
That said, I think the error you're getting is because you're setting the SelectedIndex to 0 when the ComboBox has no items in it. You're telling it to select the first one, but there's nothing to select. You should add the item first, then select it.

Windows Phone - SyndicationFeed issue

I need to do application for Windows Phone for school project. I've followed tutorial to do RSS reader, but it doesn't work and I don't know why.
I'm getting following error (after it runs):
System.Windows.Data Error: BindingExpression path error: 'Items'
property not found on
'Expression.Blend.SampleData.JustTestingData.JustTestingData'
'Expression.Blend.SampleData.JustTestingData.JustTestingData'
(HashCode=12963143). BindingExpression: Path='Items'
DataItem='Expression.Blend.SampleData.JustTestingData.JustTestingData'
(HashCode=12963143); target element is
'System.Windows.Controls.ListBox' (Name='FeedContent'); target
property is 'ItemsSource' (type 'System.Collections.IEnumerable')..
Here is my .cs file:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
public void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenWriteAsync(new Uri("http://www.twojapogoda.pl/wiadomosci.xml"));
}
public void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
SyndicationFeed feed;
using (XmlReader reader = XmlReader.Create(e.Result))
{
feed = SyndicationFeed.Load(reader);
FeedContent.ItemsSource = feed.Items;
}
}
}
Here is my xaml:
<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Syndication="clr-namespace:System.ServiceModel.Syndication;assembly=System.ServiceModel.Syndication"
x:Class="JustTestIt.MainPage"
mc:Ignorable="d"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="ItemTemplate">
<StackPanel>
<CheckBox IsChecked="{Binding date, Mode=TwoWay}"/>
<TextBlock Text="{Binding title}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="ItemTemplate1">
<StackPanel>
<CheckBox IsChecked="{Binding date, Mode=TwoWay}"/>
<TextBlock Text="{Binding title}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="ItemTemplate2">
<StackPanel Width="381">
<TextBlock Text="{Binding title}" FontSize="32" Foreground="#FFFF8B00" Margin="0,0,10,0" FontFamily="Segoe WP Semibold"/>
<TextBlock Text="{Binding date}" Foreground="White" FontFamily="Segoe WP Light"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="SyndicationItemTemplate">
<StackPanel>
<TextBlock Text="{Binding Title.Text}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="SyndicationItemTemplate1">
<StackPanel>
<TextBlock Text="{Binding Title.Text}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="SyndicationItemTemplate2">
<StackPanel>
<TextBlock Text="{Binding Title.Text}"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<phone:PhoneApplicationPage.FontFamily>
<StaticResource ResourceKey="PhoneFontFamilyNormal"/>
</phone:PhoneApplicationPage.FontFamily>
<phone:PhoneApplicationPage.FontSize>
<StaticResource ResourceKey="PhoneFontSizeNormal"/>
</phone:PhoneApplicationPage.FontSize>
<phone:PhoneApplicationPage.Foreground>
<StaticResource ResourceKey="PhoneForegroundBrush"/>
</phone:PhoneApplicationPage.Foreground>
<Grid x:Name="LayoutRoot" Background="Transparent" DataContext="{Binding Source={StaticResource JustTestingData}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<phone:Panorama Foreground="White" FontFamily="Segoe WP Light" Background="Black">
<phone:Panorama.Title>
<TextBlock Text="JustTest it!"/>
</phone:Panorama.Title>
<phone:PanoramaItem x:Name="headers" CacheMode="{x:Null}" Header="">
<phone:PanoramaItem.RenderTransform>
<TranslateTransform/>
</phone:PanoramaItem.RenderTransform>
<Grid Margin="0">
<ListBox HorizontalAlignment="Left" ItemTemplate="{StaticResource ItemTemplate2}" ItemsSource="{Binding Collection}" VerticalAlignment="Top" Width="410"/>
</Grid>
</phone:PanoramaItem>
<phone:PanoramaItem x:Name="articles" CacheMode="{x:Null}" Header="" d:DataContext="{d:DesignData /SampleData/SyndicationFeedSampleData.xaml}">
<phone:PanoramaItem.RenderTransform>
<TranslateTransform/>
</phone:PanoramaItem.RenderTransform>
<Grid>
<ListBox x:Name="FeedContent" HorizontalAlignment="Left" ItemTemplate="{StaticResource SyndicationItemTemplate2}" ItemsSource="{Binding Items}" VerticalAlignment="Top"/>
</Grid>
</phone:PanoramaItem>
</phone:Panorama>
</Grid>
</phone:PhoneApplicationPage>
What am I doing wrong, that nothing loads from source?
I'm using blend and visual studio 2013.
Your error is on this line
<ListBox x:Name="FeedContent" HorizontalAlignment="Left" ItemTemplate="{StaticResource
SyndicationItemTemplate2}" ItemsSource="{Binding Items}" VerticalAlignment="Top"/>
The error is right here
ItemsSource="{Binding Items}"
Its saying it cant see a property named "Items"
This could be for a number of reasons. I need to see all of your CS file to give you a more specific answer
If this IS all of your cs file then the there is a HUGE problem. You have no properties....
You could start by adding this.
public ObservableCollection Items {get;set;}
Also it doesn't appear that you are setting the datacontext.
Above InitializeComponent do this.
this.DataContext = this;
Edit
Based on further evaluation of your CS file and some creative extrapolation it looks like you need to do the following.
Make your SyndicationFeed object a property
private SyndicationFeed _feed;
public SyndicationFeed feed {get{return _feed;} set{_feed = value; OnPropertyChanged("feed");}
Set your datacontext to
this.Datacontext = feed;
implement
INotifyPropertyChanged
Add a property Changed event handler
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
I am pretty sure your SyndicationFeed class needs to implement INotifyPropertyChanged also.
Either of the above two solutions should work.
The problem with the error concerned with missing property (in the code you have provided) explained AMR.
Also you should be aware that the line in the code:
FeedContent.ItemsSource = feed.Items;
would destroy the Binding you have defined in xaml.
The problem why your FeedContent isn't filled is concerned with lines:
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenWriteAsync(new Uri("http://www.twojapogoda.pl/wiadomosci.xml"));
You are subscribing to the event OpenReadCompleted, but running OpenWriteAsync() method. Your event won't get fired at all (and you probably also won't be able to write to this Uri). Change it to:
wc.OpenReadAsync(new Uri("http://www.twojapogoda.pl/wiadomosci.xml"));
then your event will be fired and SyndicationFeed loaded.

wpf check list box

I m new to wpf.In order to get check list box functionality ,I have added below xaml to my code,but there is no output in my screen.only blank,what it could be?
<TabItem Header="Samples" >
<ListBox Margin="10" Width="373" Height="236">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</TabItem>
just have a look at this basic sample
http://merill.net/2009/10/wpf-checked-listbox/
List box is a bit wired for such task..Have a look at ItemsControl.
Here is the code i use:
<ItemsControl
ItemsSource="{Binding ***}" IsTabStop="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox
Content="{Binding Name}"
IsChecked="{Binding IsSelected}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Replace your code with this
<TabItem Header="Roles" >
<ListBox Margin="10" Width="373" Height="236">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem>Hi</ListBoxItem>
</ListBox>
</TabItem>
and tell us if it still shows blank
Better still, just use the new CheckListBox control in the Extended WPF Toolkit
http://wpftoolkit.codeplex.com/wikipage?title=CheckListBox&referringTitle=Home
This might help
1.Inorder to work datatemplate you must specify itemsource, here i have bounded a Stateslist a collection of items into it.
2.Also set the Datacontext to ViewModel or the CodeBehind as datacontext.
3.Datacontext will distribute the StateList properties collection to the listbox itemsource
using codebehind -
public Window1()
{
InitializeComponent();
this.DataContext = this;
LoadData();
}
using viewmodel
public Window1()
{
InitializeComponent();
DataContext = new Window1ViewModel();
LoadData();
}
//MyItemsource Property for listbox
private ObservableCollection<States> _stateslist;
public ObservableCollection<States> StatesList
{
get { return _stateslist; }
set
{
_stateslist = value;
RaisePropertyChanged(() => StatesList);
}
}
// Sample Data Loading
public void LoadData()
{
StatesList = new ObservableCollection<States>();
StatesList.Add(new States
{
StateName = "Kerala"
});
StatesList.Add(new States
{
StateName = "Karnataka"
});
StatesList.Add(new States
{
StateName = "Goa"
});
}
Window1.Xaml
<ListBox ItemsSource="{Binding StatesList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox IsChecked="{Binding IsSelected"} Content="{Binding StateName}" />
<TextBox Text="{Binding TextBoxValue}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Check this out it isworking..you are using TabItem but you didnt define it in TabControl
<TabControl>
<TabItem Header="Tab1">
<ListBox Margin="10" Width="373" Height="236">
<ListBox.Items>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</ListBox.Items>
</ListBox>
</TabItem>
</TabControl>
If you are new in WPF use XamlPadX it will give you great help to practice out on it..

Categories