WPF - Problem with displaying an Image with BitmapImage as a source - c#

I have always been using MVVM model when creating applications with WPF and everything connected with displaying/modifying Bitmaps worked well, however this time I have decide to choose other way as I want to adjust Bitmap width and height to the control that should contain it, but something doesn't work here.
I use an event that is executed on Load as I want to get the actual height and width as said before.
Part of my code:
private BitmapImage scene;
public BitmapImage Scene
{
get { return scene; }
set { if (scene != value) { scene = value; RaisePropertyChanged("Scene"); } }
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
LoadSceneCommand = new RelayCommand(LoadScene);
GenerateTexturedCylinderCommand = new RelayCommand(GenerateTexturedCylinder);
GenerateTexturedSphereCommand = new RelayCommand(GenerateTexturedSphere);
GenerateCylinderShadingCommand = new RelayCommand(GenerateCylinderShading);
GenerateSphereShadingCommand = new RelayCommand(GenerateSphereShading);
}
private void GetSceneSize(object sender, RoutedEventArgs e)
{
object wantedNode = (Grid)this.FindName("SceneGrid");
if (wantedNode is Grid)
{
Grid imageControl = wantedNode as Grid;
sceneWidth = (int)imageControl.ActualWidth;
sceneHeight = (int)imageControl.ActualHeight;
try
{
PrepareScene();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void PrepareScene()
{
Bitmap bitmap = new Bitmap(sceneWidth, sceneHeight);
for (int x = 0; x < sceneWidth; ++x)
for (int y = 0; y < sceneHeight; ++y)
bitmap.SetPixel(x, y, Color.Black);
Scene = ImageConverters.Bitmap2BitmapImage(bitmap);
}
Xaml:
<Window x:Class="_3DRendering.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"
Loaded="GetSceneSize"
ResizeMode="NoResize"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10"/>
<RowDefinition Height="*"/>
<RowDefinition Height="10"/>
</Grid.RowDefinitions>
<Grid Grid.Column="1" Grid.Row="1" x:Name="SceneGrid">
<Image Source="{Binding Scene}" x:Name="ImageControl"/>
</Grid>
<ScrollViewer Grid.Column="3" Grid.Row="1" VerticalScrollBarVisibility="Auto">
<StackPanel>
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="0 10 0 0"/>
<Setter Property="Padding" Value="5 5 5 5"/>
</Style>
</StackPanel.Resources>
<Button Content="Textured cylinder" Command="{Binding GenerateTexturedCylinderCommand}"/>
<Button Content="Textured sphere" Command="{Binding GenerateTexturedSphereCommand}"/>
<Button Content="Cylinder shading" Command="{Binding GenerateCylinderShadingCommand}"/>
<Button Content="Sphere shading" Command="{Binding GenerateSphereShadingCommand}"/>
<Button Content="Load Scene" Command="{Binding LoadSceneCommand}"/>
<Button Content="Save Scene" Command="{Binding }"/>
</StackPanel>
</ScrollViewer>
</Grid>
As you can see I try to make the whole Bitmap black. Unfortunately the result that I get is that nothing is displayed. It is just a blank white space in the place where my Bitmap should be shown.

Related

Cannot change number of columns and rows in grid

I'm trying to make a grid where you can adjust the number of rows and columns using a slider. I have no syntax errors in my code, however it is not doing what i want it to. The grid and slider have the following XAML code:
<Window x:Class="Neural_Network_Investigation.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:Neural_Network_Investigation"
mc:Ignorable="d"
Title="MainWindow"
Height="Auto"
MaxHeight="520" MinHeight="450"
Width="Auto"
MaxWidth="700" MinWidth="630">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="300"/>
<RowDefinition Height="100"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Row="0"
Grid.Column="0"
Grid.RowSpan="4"
Grid.ColumnSpan="4" Background="Gray"/>
<Grid Grid.Column="1"
Grid.Row="1"
x:Name="NetworkGrid"
ShowGridLines="True"/>
<StackPanel Grid.Column="1"
Grid.Row="2"
Orientation="Vertical"
HorizontalAlignment="Left"
VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12"
Text="Grid Size: "/>
<TextBlock x:Name="GridSizeText"
FontSize="12" Text=""
MinWidth="15"/>
<Slider x:Name="GridSizeSlider"
Minimum="4" Maximum="20"
TickPlacement="BottomRight"
TickFrequency="1"
IsSnapToTickEnabled="True"
Width="100"
ValueChanged="GridSizeSlider_ValueChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
</StackPanel>
</StackPanel>
</Grid>
</Window>
When the slider is changed, I want the number of rows and columns in NetworkGrid to be updated to match:
private void GridSizeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
var GridSize = (int)GridSizeSlider.Value;
GridSizeText.Text = GridSize.ToString();
NetworkGrid.ColumnDefinitions.Clear();
NetworkGrid.RowDefinitions.Clear();
double SquareWidth = NetworkGrid.Width / GridSize;
double SquareHeight = NetworkGrid.Height / GridSize;
for(int columnNumber = 0; columnNumber < GridSize; columnNumber++)
{
var column = new ColumnDefinition();
NetworkGrid.ColumnDefinitions.Add(column);
for (int rowNumber = 0; rowNumber < GridSize; rowNumber++)
{
var row = new RowDefinition();
NetworkGrid.RowDefinitions.Add(row);
var square = new Border();
square.Background = Brushes.Black;
square.SetValue(Grid.ColumnProperty, columnNumber);
square.SetValue(Grid.RowProperty, rowNumber);
}
}
}
When I run the program, I see nothing despite ShowGridLines being enabled. This means that it is not adding the columns and rows to the grid. How do I fix this?
I have used code from this article: How to add rows and columns to a WPF Grid programmatically
I have also checked out this blog showcasing a class that allows you to draw a Grid with a dynamic number of rows or columns, however i cannot get my head around how to use the class in my own program.

Show controls in Scrollviewer row along the Scrollbar

So I have this scenario in which I am showing a Grid inside a ScrollViewer.
I want to show a combobox and an image along the scrollbar in a way that it doesn't effect the scrolling functionality,
Something like this:
Currently whenever the scrollviewer becomes visible it appears in a new row, how can I show it along the controls in the same row?
Here is my xaml design:
<DockPanel LastChildFill="True">
<!--Top Panel-->
<Grid DockPanel.Dock="Top">
--GridContent
</Grid>
<!--Bottom Panel-->
<Grid DockPanel.Dock="Bottom">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ComboBox Grid.Column ="0">
</ComboBox>
<Image Grid.Column="1">
</Image>
</Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto" HorizontalAlignment="Stretch"
VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch" >
<Grid
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
-- Grid Content
</Grid>
</ScrollViewer>
</DockPanel>
Currently it appears like this :
I haven't looked at doing this in XAML, but you can do it like this in the code behind:
public partial class MainWindow : Window
{
private void IncrementColumn(UIElement element)
{
Grid.SetColumn(element, Grid.GetColumn(element) + 1);
}
public MainWindow()
{
InitializeComponent();
scrollPanel.ApplyTemplate();
var horizontal = scrollPanel.Template.FindName("PART_HorizontalScrollBar", scrollPanel) as ScrollBar;
var vertical = scrollPanel.Template.FindName("PART_VerticalScrollBar", scrollPanel) as ScrollBar;
var presenter = scrollPanel.Template.FindName("PART_ScrollContentPresenter", scrollPanel) as ScrollContentPresenter;
var corner = scrollPanel.Template.FindName("Corner", scrollPanel) as Rectangle;
var grid = corner.Parent as Grid;
grid.ColumnDefinitions.Insert(0, new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
IncrementColumn(horizontal);
IncrementColumn(vertical);
IncrementColumn(corner);
Grid.SetColumnSpan(presenter, 2);
var panel = new StackPanel() { Orientation = Orientation.Horizontal };
panel.Children.Add(new ComboBox());
panel.Children.Add(new Image());
Grid.SetRow(panel, 1);
Grid.SetColumn(panel, 0);
grid.Children.Add(panel);
}
}
Here's the XAML to go with it:
<Window x:Class="WpfApplication1.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"
Title="MainWindow" Height="150" Width="525">
<ScrollViewer
Name="scrollPanel"
HorizontalScrollBarVisibility="Visible"
HorizontalAlignment="Stretch"
VerticalScrollBarVisibility="Auto"
VerticalAlignment="Stretch">
<Grid
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Image Source="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"/>
</Grid>
</ScrollViewer>
</Window>

Creating and filling a NxN grid in UWP Xaml

I am trying to create a UWP puzzle game, I want to cut the picture into n parts and then show the pieces in a grid.
My problem is, how to force a certain NxN style. Right now I have to maximize the window in order to see a 3x3 grid, if I shrink either side, it will converge to a 2 column, 1 column grid. Is there a way to handle this?
This is what I have done, I know the RowDefinition is manually right now, until I figure out a better way to do that.
<UserControl
x:Class="PictureSplitter.Views.PictureView"
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"
d:DesignHeight="300"
d:DesignWidth="400">
<GridView ItemsSource="{Binding Splitter.PuzzlePositions}">
<GridView.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="2">
<Grid x:Name="picGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Source="{Binding Piece.ImageSource}" />
</Grid>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</UserControl>
This are two example images:
There are probably couple of ways to do that, here is another one. I've modified the UserControl so that it automatically adjusts items size to show them as square grid, when page size changes and/or collection changes.
The UserControl XAML code:
<UserControl
x:Class="MyControls.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyControls"
Name="myControl">
<GridView Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" ItemsSource="{Binding ElementName=myControl, Path=Items}"
Width="{Binding ElementName=myControl, Path=CurrentWidth}" HorizontalAlignment="Center"
Height="{Binding Width, RelativeSource={RelativeSource Self}}">
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="Margin" Value="0"/>
</Style>
</GridView.ItemContainerStyle>
<GridView.ItemTemplate>
<DataTemplate>
<Border Padding="10" Width="{Binding ElementName=myControl, Path=ElementSize}" Height="{Binding ElementName=Width, RelativeSource={RelativeSource Self}}">
<Border BorderBrush="Red" BorderThickness="3">
<Image Source="ms-appx:///Assets/StoreLogo.png" Stretch="UniformToFill"/>
</Border>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</UserControl>
UserControl code behind:
public sealed partial class MyUserControl : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaiseProperty(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
public IList Items
{
get { return (IList)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(IList), typeof(MyUserControl),
new PropertyMetadata(0, (s, e) =>
{
if (Math.Sqrt((e.NewValue as IList).Count) % 1 != 0)
Debug.WriteLine("Bad Collection");
}));
public void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (Math.Sqrt(Items.Count) % 1 != 0) Debug.WriteLine("Bad Collection");
RaiseProperty(nameof(ElementSize));
}
private double currentWidth;
public double CurrentWidth
{
get { return currentWidth; }
set { currentWidth = value; RaiseProperty(nameof(CurrentWidth)); RaiseProperty(nameof(ElementSize)); }
}
public double ElementSize => (int)(currentWidth / (int)Math.Sqrt(Items.Count)) - 1;
public MyUserControl()
{
this.InitializeComponent();
}
}
The MainPage XAML:
<Grid>
<local:MyUserControl x:Name="myControl" Items="{Binding MyItems}"/>
<Button Content="Add" Click="Button_Click"/>
</Grid>
MainPage code behind:
public sealed partial class MainPage : Page
{
private ObservableCollection<int> myItems = new ObservableCollection<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
public ObservableCollection<int> MyItems
{
get { return myItems; }
set { myItems = value; }
}
public MainPage()
{
this.InitializeComponent();
DataContext = this;
MyItems.CollectionChanged += myControl.Items_CollectionChanged;
}
protected override Size MeasureOverride(Size availableSize)
{
myControl.CurrentWidth = Math.Min(availableSize.Height, availableSize.Width);
return base.MeasureOverride(availableSize);
}
private void Button_Click(object sender, RoutedEventArgs e) => MyItems.Add(3);
}
The program starts with "Bad Collection" - there are 8 items, so you can't make a square grid from them, but as soon as you click the provided button - the collection's count changes to 9 and the grid should update itself.
It looks like you are doing this by way of MVVM, so I think you need to have a property for your Rows and Columns from your ViewModel. And then you need to have a Converter to supply the coordinate for your pieces .... OR an Attached property.
This will give you an idea:
<Window.Resources>
<System:Int64 x:Key="X">3</System:Int64>
<System:Int64 x:Key="Y">3</System:Int64>
</Window.Resources>
<Grid x:Name="myGrid" Loaded="Grid_Loaded">
// You can bind column and row
// <Button Content="image1" Grid.Column="{Binding column}" Grid.Row="{Binding row}"/>
<Button Content="image1" Grid.Column="0" Grid.Row="0"/>
<Button Content="image2" Grid.Column="1" Grid.Row="0"/>
<Button Content="image3" Grid.Column="2" Grid.Row="0"/>
<Button Content="image4" Grid.Column="0" Grid.Row="1"/>
<Button Content="image5" Grid.Column="1" Grid.Row="1"/>
<Button Content="image6" Grid.Column="2" Grid.Row="1"/>
<Button Content="image7" Grid.Column="0" Grid.Row="2"/>
<Button Content="image8" Grid.Column="1" Grid.Row="2"/>
<Button Content="image9" Grid.Column="2" Grid.Row="2"/>
</Grid>
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
Int64 X = (Int64) this.FindResource("X");
Int64 Y = (Int64) this.FindResource("Y");
for (Int64 i = 0; i < X; i++)
{
ColumnDefinition c = new ColumnDefinition();
myGrid.ColumnDefinitions.Add(c);
}
for (Int64 i = 0; i < (int)Y; i++)
{
RowDefinition r = new RowDefinition();
myGrid.RowDefinitions.Add(r);
}
}
I have used a ListView with GridView as it's View property. And it is working fine.
<ListView x:Name="ImageList" Width="210" Height="210">
<ListView.View>
<GridView>
<GridView.ColumnHeaderContainerStyle>
<Style TargetType="Control">
<Setter Property="Visibility" Value="Collapsed"/>
</Style>
</GridView.ColumnHeaderContainerStyle>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding sq1}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding sq2}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding sq3}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
var imgBox = new BitmapImage(new Uri(#"/images/cellbkg.jpg", UriKind.Relative));
var source = new[] { new { sq1 = imgBox, sq2 = imgBox, sq3 = imgBox }, new { sq1 = imgBox, sq2 = imgBox, sq3 = imgBox }, new { sq1 = imgBox, sq2 = imgBox, sq3 = imgBox } };
ImageList.ItemsSource = source;
This code produces below output, and don't get collapsed if you reduce window size :
If this is what you want, you can add columns dynamically using below approach. For NxN matrix, you have to add only N columns, binding will take care of rest :
GridView view = (GridView)ImageList.View;
view.Columns.Add(new GridViewColumn());

Detecting OrientationChanged Event in Portrait Mode

On Windows Phone 8.1, I am doing an OrientationChanged event where a media element will change to full window when in landscape mode which works perfectly. But when I rotate to portrait, it doesn't back out of full window to its width of the screen in portrait mode. In fact, it doesn't do anything. The problem is that the Event Handler detects the landscape orientation but not the portrait orientation? What am I missing? MediaElement seems stuck in IsFullWindow = true and never checks again for orientationchanged event method.
XAML:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Width="Auto" Height="250" Background="Green" Orientation="Horizontal" VerticalAlignment="Top">
<MediaElement x:Name="media"
Source="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
AutoPlay="True"
AreTransportControlsEnabled="True"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Stretch="UniformToFill"
Width="Auto"
Height="Auto"
/>
</StackPanel>
</Grid>
C#
void MainPage_OrientationChanged(DisplayInformation sender, object args)
{
var orientation = DisplayInformation.GetForCurrentView().CurrentOrientation; // get the current orientation of the display
if (orientation == DisplayOrientations.Landscape || orientation == DisplayOrientations.LandscapeFlipped) // if the orientation is landscape...
{
media.IsFullWindow = true; // puts the media element in full screen while in landscape
}
else //if (orientation == DisplayOrientations.Portrait || orientation == DisplayOrientations.PortraitFlipped)
{
media.IsFullWindow = false; // puts the media element out of full screen in portrait
//media.Width = Window.Current.Bounds.Width; // set bounds of video width to width of screen
}
}
In your XAML you can write these lines of 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"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Top">
<MediaElement x:Name="media"
Source="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
AutoPlay="True"
AreTransportControlsEnabled="True"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Stretch="Uniform" />
</StackPanel>
</Grid>
</Page>
In your code-behind you can call the OrientationChanged event of SimpleOrientationSensor class:
namespace App1
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
SimpleOrientationSensor.GetDefault().OrientationChanged += (s, a) =>
Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
if (a.Orientation == SimpleOrientation.NotRotated || a.Orientation == SimpleOrientation.Faceup || a.Orientation == SimpleOrientation.Facedown)
{
media.IsFullWindow = false;
}
else
{
media.IsFullWindow = true;
}
});
}
}
}
Don't forget to include Windows.Devices.Sensors reference ;)

Dynamically adding contents to stackpanel in code behind

Am trying to add Set of labels and images in a stackpanel in code behind.And finally am attaching that stackpanel to particular column of a grid control.My expected output should be like
<image><label>
combination
but my output is like it displays the label in first column of grid and the image in the next column.(I was not able to add the snapshots since i dont have enough reputations)
XAML code
<Window x:Class="Ping.MainWindow" WindowStyle="ThreeDBorderWindow" Icon="F:\ChatApplication\Ping\Ping\Images\title.ico" Cursor="Pen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Ping - Connected by alphabets" Height="450" Width="750" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight" >
<Grid Name="grid_window">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GridSplitter HorizontalAlignment="Right"
VerticalAlignment="Stretch"
Grid.Column="1" ResizeBehavior="PreviousAndNext"
Width="5" Background="#FFBCBCBC"/>
<TabControl Grid.ColumnSpan="2" Name="tab_control" BorderBrush="Cornsilk" BorderThickness="4" HorizontalAlignment="Left" Height="419" Margin="227,0,0,0" VerticalAlignment="Top" Width="515">
<TabItem Header="Home" BorderBrush="Green"/>
</TabControl>
</Grid>
code behind
public MainWindow()
{
InitializeComponent();
DBCoding dbobj = new DBCoding();
//Contains names {"Dhivi","Walle"}
List<string> online = new List<string>();
online = dbobj.onlineUsers();
StackPanel myStackPanel = new StackPanel();
myStackPanel.Orientation = Orientation.Vertical;
foreach (var item in online)
{
Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("F:\\ChatApplication\\Ping\\Ping\\Images\\visible.png"));
myImage.Width = 10;
myImage.Height = 10;
//myImage.Margin = new Thickness(-10,0,-80,0);
myImage.Height = 10;
Label user = new Label();
user.Content = item.ToString();
myStackPanel.Children.Add(myImage);
myStackPanel.Children.Add(user);
}
grid_window.Children.Add(myStackPanel);
Grid.SetColumnSpan(myStackPanel, 1);
Grid.SetColumn(myStackPanel, 0);
}
Can anybody tell me the solution.
Here's how your code should look like, using data binding, an ItemsControl and a DataTemplate:
XAML
<Window x:Class="Ping.MainWindow" WindowStyle="ThreeDBorderWindow" Icon="F:\ChatApplication\Ping\Ping\Images\title.ico" Cursor="Pen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Ping - Connected by alphabets" Height="450" Width="750" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight" >
<Grid Name="grid_window">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GridSplitter HorizontalAlignment="Right"
VerticalAlignment="Stretch"
Grid.Column="1" ResizeBehavior="PreviousAndNext"
Width="5" Background="#FFBCBCBC"/>
<TabControl Grid.ColumnSpan="2" Name="tab_control" BorderBrush="Cornsilk" BorderThickness="4" HorizontalAlignment="Left" Height="419" Margin="227,0,0,0" VerticalAlignment="Top" Width="515">
<TabItem Header="Home" BorderBrush="Green"/>
</TabControl>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel>
<!-- You really should add the image as a resource to the project -->
<Image Source="F:\ChatApplication\Ping\Ping\Images\visible.png"
Width="10" Height="10" />
<TextBlock Text="{Binding}" />
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
C#
public MainWindow()
{
InitializeComponent();
DBCoding dbobj = new DBCoding();
List<string> online = dbobj.onlineUsers();
DataContext = online;
}

Categories

Resources