I have a window
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:GRHelper="clr-namespace:Enertek.GRHelper;assembly=Enertek.GRHelper" xmlns:local="clr-namespace:EneGR" x:Class="EneGR.SearchWindow"
Title="Main Window" Height="274.753" Width="322.345" Icon="icon.ico">
<Window.OpacityMask>
<RadialGradientBrush>
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</RadialGradientBrush>
</Window.OpacityMask>
<Window.BorderBrush>
<ImageBrush Stretch="None" TileMode="FlipXY"/>
</Window.BorderBrush>
<Grid RenderTransformOrigin="0.5,0.5" Margin="0,0,2,6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto" MinWidth="120"/>
<ColumnDefinition Width="65"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Button x:Name="SearchButton" Content="Search" Grid.Column="3" Margin="0,62,0,0" VerticalAlignment="Top" Height="23" RenderTransformOrigin="0.6,0.458" FontWeight="Bold"
Click="SearchButton_Click"/>
<Label x:Name="SearchLabel" Content="Enter object's name or its part in the field below:" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Grid.ColumnSpan="4" Width="285" Height="36"/>
<Button x:Name="SearchCancel" Grid.ColumnSpan="2" Content="Cancel" HorizontalAlignment="Left" Margin="0,61,0,0" VerticalAlignment="Top" Width="120" Height="24" FontWeight="Bold"
Click=" SearchCancel_Click"/>
<TreeView Grid.Column ="1" ItemsSource="{Binding objs}" Margin="0,101,3,40" Grid.ColumnSpan="3" Background="White">
<TreeView.DataContext>
<local:MyTreeData/>
</TreeView.DataContext>
<TreeView.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Checked, Mode=TwoWay}" Content="{Binding TagName}" Checked="CheckBox_Checked"/>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Button x:Name="Rename" Content="Rename" Grid.Column="2" HorizontalAlignment="Left" Margin="62,212,0,0" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2" Click="Rename_Click" FontWeight="Bold"/>
<TextBox x:Name="TagNameBox" Grid.ColumnSpan="3" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="10,33,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="285"/>
<Button Content="Button" HorizontalAlignment="Left" Height="100" Margin="-106,257,0,-115" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
The code behind:
namespace EneGR
{
public class MyTreeData
{
public ObservableCollection<GRObject> objs { get; set; }
private bool allAreChecked = false;
public MyTreeData()
{
objs = new ObservableCollection<GRObject>();
}
public bool AllAreChecked
{
get
{
return allAreChecked;
}
set
{
allAreChecked = value;
}
}
}
/// <summary>
/// Interaction logic for SearchWindow.xaml
/// </summary>
public partial class SearchWindow : Window
{
GRGalaxy galaxy = EneGR.LoginWin.galaxy;
List <GRObject> ObjsToRename = null;
public MyTreeData TreeData = new MyTreeData();
public SearchWindow()
{
InitializeComponent();
DataContext = TreeData;
}
private void SearchCancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void SearchButton_Click(object sender, RoutedEventArgs e)
{
string TagName = TagNameBox.Text;
IEnumerable<GRObject> objects = galaxy.QueryObjectsByName(TagName + '%');
MessageBox.Show(objects.Count().ToString() + " " + "Objects found" );
foreach (GRObject obj in objects)
{
TreeData.objs.Add(obj);
};
}
private void Rename_Click(object sender, RoutedEventArgs e)
{
galaxy.RenameCheckedObjects(ObjsToRename);
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
//add checked object to ienumerable collection ObjsToRename;
}
}
}
I binded objects from observable collection TreeData.objs to TreeView with CheckBoxes but they never show up in the window. I cannot understand what is wrong. IEnumerable objects is not null.
You can remove this code :
<TreeView.DataContext>
<local:MyTreeData/>
</TreeView.DataContext>
... which creates a new instance of MyTreeData and sets the TreeView's DataContext to it.
The context of your treeview is already set to the MyTreeData you want to use (because of DataContext inheritance) :
public SearchWindow()
{
InitializeComponent();
DataContext = TreeData;
}
Related
I have a counter which increments depending on a foreach Loop from:
public partial class UserControlCounter : UserControl, INotifyPropertyChanged
{
private int _scanStatusCounter;
public int ScanStatusCounter
{
get { return _scanStatusCounter; }
set { _scanStatusCounter = value; NotifyPropertyChanged(); }
}
public UserControlCounter()
{
InitializeComponent();
DataContext = this;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await Task.Run(getAll);
scanStatus.Text = "Persons " + ScanStatusCounter.ToString();
}
private async void getAll()
{
//grab data and iterate it
string[] string_array = new string[] { "a", "b", "c", "d", "e" }; // type = System.String[]
foreach (var i in string_array)
{
ScanStatusCounter++;
await Task.Delay(100);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
and the Xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="myListBox" Height="40" ></ListBox>
<TextBlock Grid.Row="0" Grid.Column="1" Name="scanStatus" Height="40" Text="{Binding Path=ScanStatusCounter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
<Button Grid.Row="0" Grid.Column="2" Click="Button_Click" Height="40">Click Me</Button>
</Grid>
That works fine and increments "live", but my problem is that I need to get that now running inside a more complex Data Template.
I've tried to inject the Counter onClick with:
private async void Button_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
var contentPresenter = (btn.TemplatedParent as ContentPresenter);
var ppStatusCounter = contentPresenter.ContentTemplate.FindName("scanStatus", contentPresenter) as TextBlock;
ppStatusCounter.Text = "Entrys found: " + ScanStatusCounter.ToString();
}
But then I get the Value only onClick not like a live incrementing Counter, that's my Data Template:
<UserControl.Resources>
<c1:NameList x:Key="NameListData"/>
<DataTemplate x:Key="NameItemTemplate">
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Domaine"/>
<TextBox Grid.Row="1" Grid.Column="0" x:Name="txtDomainName" Text="{Binding Path=DomaineName}" Margin="0,0,5,0"></TextBox>
<Button Grid.Row="1" Grid.Column="1" Width="100" Height="30" Margin="5,5,5,5" x:Name="btnNames" Click="Button_Click" Content="Start Scan" />
<Grid Grid.Column="2" Grid.Row="1" Height="20">
<ProgressBar x:Name="pbStatus" Height="20" Width="100" Minimum="0" Maximum="100" Visibility="Hidden"/>
<TextBlock x:Name="pbStatusText" HorizontalAlignment="Center" VerticalAlignment="Center" Text="Scanning" Visibility="Hidden"/>
</Grid>
<TextBlock Grid.Column="3" Grid.Row="1" Name="scanStatus" Text="{Binding Path=ScanStatusCounter, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid>
<StackPanel Orientation="Horizontal" VerticalAlignment="top">
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
<ListBox x:Name="lstDomainNames"
Margin="5,5,5,5"
ItemsSource="{Binding Source={StaticResource NameListData}}"
ItemTemplate="{StaticResource NameItemTemplate}"
IsSynchronizedWithCurrentItem="True"/>
</StackPanel>
</StackPanel>
</Grid>
that's my Data Source Class, not much there:
public partial class NameList : ObservableCollection<SetCredentials>
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public NameList() : base()
{
using var forest = Forest.GetCurrentForest();
Forest currentForest = Forest.GetCurrentForest();
DomainCollection domains = currentForest.Domains;
foreach (Domain objDomain in domains)
{
Add(new SetCredentials(objDomain.ToString()));
}
}
}
public class SetCredentials
{
private string domainName;
public SetCredentials(string domain)
{
this.domainName = domain;
}
public string DomaineName
{
get { return domainName; }
set { domainName = value; }
}
}
Do I have to add a second Data Binding source to my ItemSource or do I need another approach for this, for example in my TextBox Binding?
I want to add ListViewItem with changed details like image's link, text in textbox etc. How can I do it?
<ListView VerticalAlignment="Bottom" Margin="10" Height="170" Foreground="LightSteelBlue">
<ListViewItem>
<StackPanel Orientation="Horizontal">
<TextBlock Text="01" VerticalAlignment="Center"/>
<Ellipse Margin="20,0" Width="30" Height="30" VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush ImageSource="images/pobrane.jpg"/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Text="Three Days Grace - I Hate Everything About You (Official Music Video)" Width="115" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
<TextBlock Text="3:45" Margin="10,0" VerticalAlignment="Center" />
</StackPanel>
</ListViewItem>
</ListView>
I want to make function which will add the same code like i showed you with changed details.
You can use the ItemTemplate and the ItemsSource properties of the WPF Listview and the Binding concepts.
Just for an example, starting from your question:
You can add the following code to the MainWindow files of a new WPF project:
The MainWindow.xaml file should look like this:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Click="Button_Click"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="10"
Content="Add item"/>
<ListView VerticalAlignment="Bottom"
Margin="10"
Height="170"
ItemsSource="{Binding Tracks}"
Foreground="LightSteelBlue">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"
VerticalAlignment="Center" />
<Ellipse Margin="20,0"
Width="30"
Height="30"
VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush ImageSource="{Binding Image}" />
</Ellipse.Fill>
</Ellipse>
<TextBlock Text="{Binding Name}"
Width="115"
TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
<TextBlock Text="{Binding Length}"
Margin="10,0"
VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
And the MainWindow.xaml.cs file should look like this:
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Track> Tracks { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Tracks = new ObservableCollection<Track>();
AddTrack("01","Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg")));
}
public void AddTrack (string number, string name, string length, ImageSource image)
{
var track = new Track();
track.Number = number;
track.Name = name;
track.Length = length;
track.Image = image;
Tracks.Add(track);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AddTrack("01", "Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg")));
}
}
public class Track
{
public string Number { get; set; }
public string Name { get; set; }
public string Length { get; set; }
public ImageSource Image { get; set; }
}
}
Of course, this is just as a starting point. You should go on searching and reading the MVVM concepts and move the logic to a viewmodel.
I have a list on page one with car objects. I want to click on a car from the list and click a button which will send the selected car to a list on another uwp page.
I am trying to put the listCar.selecteditems in an empty list I created called purchase and display purchase on page 2. With the code I have at the moment, it is only displaying ProjectName_Car in the list on page 2.
Any help on displaying this properly is appreciated.
Page1.xaml.cs
private void Add_Click(object sender, RoutedEventArgs e)
{
var query = listCars.SelectedItems.ToList().Cast<Car>();
foreach (var item in query)
{
purchase.Add(item);
}
liistCar.ItemsSource = purchase;
Frame.Navigate(typeof(Page2), listCar.Items);
}
Page2.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
lstCars.ItemsSource = e.Parameter as List<Car> ;
}
Edit: Page1.xaml
<ListBox Name="listCars" ItemsSource="{x:Bind cars}" >
<ListBox.ItemTemplate>
<DataTemplate x:DataType="Car">
<StackPanel Padding="20">
<Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind imgCar}" />
<TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind Name}" Style="{StaticResource HeaderTextBlockStyle}"/>
<TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{Binding Price}" /></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This one transfers your selected car list object to next page as parameter with all its properties.
MainPage.xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="YourPage"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel x:Name="Stacky" HorizontalAlignment="Stretch" Background="Aqua" VerticalAlignment="Stretch">
<ListBox Name="listCars" ItemsSource="{x:Bind cars}" SelectionMode="Multiple" Grid.Column="0" Grid.Row="1" Background="#FFF1EFEF" Opacity="0.7" Foreground="Black" Margin="10,10,94,10" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="local:Car">
<StackPanel Padding="20" BorderThickness="2" BorderBrush="Black">
<Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind imgCar}" />
<TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind name}" Style="{StaticResource HeaderTextBlockStyle}"/>
<TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{x:Bind price}" /></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Done Selecting" Click="Add_Click"></Button>
</StackPanel>
</Page>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
List<Car> cars = new List<Car>();
public MainPage()
{
cars.Add(new Car() { imgCar = "ms-appx:///Assets/1.jpg", name = "Car1", price = "10000" });
cars.Add(new Car() { imgCar = "ms-appx:///Assets/2.jpg", name = "Car2", price = "10001" });
cars.Add(new Car() { imgCar = "ms-appx:///Assets/3.jpg", name = "Car3", price = "10002" });
this.InitializeComponent();
}
private void Add_Click(object sender, RoutedEventArgs e)
{
List<Car> mySelectedItems = new List<Car>();
foreach (Car item in listCars.SelectedItems)
{
mySelectedItems.Add(item);
}
Frame.Navigate(typeof(Page2), mySelectedItems);
}
}
public class Car
{
public string imgCar { get; set; }
public string name { get; set; }
public string price { get; set; }
}
Page2.xaml
<Page
x:Class="App1.Page2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<ListBox Name="listCars" SelectionMode="Multiple" Grid.Column="0" Grid.Row="1" Background="#FFF1EFEF" Opacity="0.7" Foreground="Black" Margin="10,10,94,10" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="local:Car">
<StackPanel Padding="20" BorderThickness="2" BorderBrush="Black">
<Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind imgCar}" />
<TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind name}" Style="{StaticResource HeaderTextBlockStyle}"/>
<TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{x:Bind price}" /></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Page>
Page2.xaml.cs
public sealed partial class Page2 : Page
{
public Page2()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var items = e.Parameter as List<Car>;
listCars.ItemsSource = items;
base.OnNavigatedTo(e);
}
}
I have created a view model which has a single property for a student model, that I am then binding to a control in my XAML. But nothing is appearing when I execute the application.
I am setting data context in my app.xaml.cs as follows:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Registrationformusinemvvm.MainWindow window = new MainWindow();
VMUser VM = new VMUser();
window.DataContext = VM;
window.Show();
}
Why is the binding not working?
This is my view model:
public class VMUser:BaseClass
{
private student _currentStudent;
public student CurrentStudent
{
get { return _currentStudent; }
set {
_currentStudent = value;
OnPropertyChanged("CurrentStudent");
}
}
}
My Student model class:
public class student:BaseClass
{
private string name="sumit";
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
private int rollNum;
public int RollNum
{
get { return rollNum; }
set { rollNum = value;OnPropertyChanged("RollNum"); }
}
private int phNum;
public int PhNum
{
get { return phNum; }
set { phNum = value;OnPropertyChanged("PhNum"); }
}
private string sub;
public string Sub
{
get { return sub; }
set { sub = value;OnPropertyChanged("Sub"); }
}
}
My XAML:
<Window x:Class="Registrationformusinemvvm.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Registrationformusinemvvm"
xmlns:vm="clr-namespace:Registrationformusinemvvm.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!--<Window.DataContext>
<vm:VMUser/>
</Window.DataContext>-->
<Window.Resources>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Name" Grid.Column="0" Grid.Row="0" FontSize="14"
FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBlock Text="Roll Number" Grid.Column="0" Grid.Row="1" FontSize="14"
FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBlock Text="Subject" Grid.Column="0" Grid.Row="2" FontSize="14"
FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBlock Text="Phone Number" Grid.Column="0" Grid.Row="3"
FontSize="14" FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBox Name="tbName" Text="{Binding CurrentStudent.Name,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Grid.Row="0"
Width="120" Height="30" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<TextBox Name="tbRollnum" Text="{Binding CurrentStudent.RollNum}"
Grid.Column="1" Grid.Row="1" Width="120" Height="30"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Name="tbSub" Text="{Binding CurrentStudent.Sub}"
Grid.Column="1" Grid.Row="2" Width="120" Height="30"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Name="tbPh" Text="{Binding CurrentStudent.PhNum}"
Grid.Column="1" Grid.Row="3" Width="120" Height="30"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Name="tbSubmit" Content="Submit" Grid.ColumnSpan="3"
Grid.Row="4" Height="30" Width="100" HorizontalAlignment="Center"/>
</Grid>
</Window>
My guess is that your binding isn't working because your _currentStudent is null by default. Initialize your _currentStudent if null.
public student CurrentStudent
{
get { return _currentStudent = (_currentStudent ?? new student()); }
set
{
_currentStudent = value; OnPropertyChanged("CurrentStudent");
}
}
You need to add OnPropertyChanged in your model class.
void OnPropertyChanged(string prop)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
public event PropertyChangedEventHandler PropertyChanged;
As per your above code you cant assigned the value to CurrentStudent Property so
can you please check do you have the value to CurrentStudent property.
Thank you for your question
Remove StartupUri="YourXamlFile.xaml" from App.Xaml
First time using a ListBox and after following this , I'm having issues having data actually display. The ListBox is just empty and white with no text in it.
I made a separate textbox to test an individual "Tweet" object out and it is indeed outputting what I want it to. I think my issue either lies in XAML or Tweets. But nothing looks out of place.
Tracing reveals that Tweets successfully adds a proper Tweet object with what I need. But my ListBox Count is always 0.
<Grid Opacity="0.8">
<Grid.Resources>
<local:Tweets x:Key="tweets"/>
</Grid.Resources>
<Rectangle Fill="Gray" Margin="1523,0,0,729" Height="321" Width="389">
<Rectangle.Effect>
<DropShadowEffect/>
</Rectangle.Effect></Rectangle>
<ListBox ItemsSource="{StaticResource tweets}" Height="321" Margin="340,40,1096,0" x:Name="twitterBox" VerticalAlignment="Top" Width="476">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
In my cs:
public class Tweet
{
public String imgSrc { get; set; }
public String user { get; set; }
public String tweet { get; set; }
public Tweet(String user, String tweet, String img)
{
this.imgSrc = img;
this.user = user;
this.tweet = tweet;
}
}
public class Tweets : ObservableCollection<Tweet>
{
public Tweets()
{
}
public void addTweet(Tweet tweet)
{
Add(tweet);
}
}
public void SomeFunction()
{
Tweets myTwitter = new Tweets();
myTwitter.addTweet(new Tweet(tweet.User.ScreenName, tweet.Text, tweet.User.ProfileImageUrl));
}
ItemTemplate code is ok but you should remove this Margin="1523,0,0,729".
ListBox is empty because items source is empty. You should add some items.
To add items in XAML you should add default constructor to Tweet class.
public class Tweet
{
public String imgSrc { get; set; }
public String user { get; set; }
public String tweet { get; set; }
public Tweet(){}
public Tweet(String user, String tweet, String img)
{
this.imgSrc = img;
this.user = user;
this.tweet = tweet;
}
}
And now you can write something like this:
...
<Grid.Resources>
<local:Tweets x:Key="tweets">
<local:Tweet imgSrc="imgSrc1" user="user1" tweet="tweet1" />
<local:Tweet imgSrc="imgSrc2" user="user2" tweet="tweet2" />
</local:Tweets>
</Grid.Resources>
...
Result:
Add items in code-behind.
To do that you should use function: FindResource (msdn).
XAML:
<Grid Name="mainGrid" Opacity="0.8">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.Resources>
<local:Tweets x:Key="tweets">
<local:Tweet imgSrc="imgSrc1" user="user1" tweet="tweet1" />
<local:Tweet imgSrc="imgSrc2" user="user2" tweet="tweet2" />
</local:Tweets>
</Grid.Resources>
<Button Content="Add new item" Click="Button_Click" />
<ListBox x:Name="twitterBox" ItemsSource="{StaticResource tweets}"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
var coll = mainGrid.FindResource("tweets") as Tweets;
if (coll != null)
{
coll.Add(new Tweet("user", "name", "url"));
}
}
Second solution:
The better solution will be if you will create an instance of class Tweets in code behind.
XAML:
<Grid Name="mainGrid" Opacity="0.8">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Add new item" Click="Button_Click" />
<ListBox x:Name="twitterBox" ItemsSource="{Binding tweets}"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
tweets = new Tweets();
tweets.Add(new Tweet("user1", "name1", "url1"));
tweets.Add(new Tweet("user2", "name2", "url2"));
tweets.Add(new Tweet("user3", "name3", "url3"));
this.DataContext = this;
}
public Tweets tweets { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
tweets.Add(new Tweet("user4", "name4", "url4"));
}
}
You add tweets to a different collection than the one displayed by the listbox.