I have been trying to add items to a comboxbox but cannot seem to get the code behind file to recognize the combobox added to the xaml. I am pretty sure I am missing something simple. Basically the xaml here illustrates an empty combobox. The code behind executes the service, waits for json to come back and deserialize it. Unfortunately I cannot get
xaml:
<navigation:Page x:Class="Growing.Views.Room"
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"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
d:DesignWidth="950" d:DesignHeight="480"
Title="Home" Style="{StaticResource PageStyle}" DataContext="{Binding}" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" ShowGridLines="True" Background="#FF631C00">
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<Rectangle Height="298" HorizontalAlignment="Left" Margin="195,94,0,0" Name="rect" Stroke="Black" StrokeThickness="2" VerticalAlignment="Top" Width="582" Fill="#FFAAAAAA" RadiusY="0.25" RadiusX="0.25" />
<sdk:Label Height="38" HorizontalAlignment="Left" Margin="387,160,0,0" Name="label1" VerticalAlignment="Top" Width="203" Content="Select a Room" FontSize="24" FontWeight="Bold" />
<sdk:Label Height="18" HorizontalAlignment="Left" Margin="312,240,0,0" Name="label2" VerticalAlignment="Top" Width="69" Content="Area:" FontSize="14" />
<ComboBox x:Name="RoomAreas" Height="23" HorizontalAlignment="Left" Margin="418,235,0,0" VerticalAlignment="Top" Width="209" />
</Grid>
The code behind:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Growing.DataConnectionRef;
namespace Growing.Views
{
public partial class Room : Page
{
public Room()
{
InitializeComponent();
//Asynchronously call the EndReceive Web Service to change the status of an existing open lot record
WebClient GRService = new WebClient();
GRService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GRService_DownloadStringCompleted);
GRService.DownloadStringAsync(new Uri("/servicestack/GetAreas", UriKind.Relative));
}
static void GRService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
List<Area> dataList = new List<Area>();
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(dataList.GetType());
dataList = ser.ReadObject(memoryStream) as List<Area>;
memoryStream.Close();
RoomAreas.ItemSource = dataList;
}
}
}
At RoomAreas.ItemSource I get an error An object reference is required for the non-static field, method, or property 'Growing.Views.Room.RoomAreas'
Sorry if this is hard to follow. Anyone have any ideas what might be going on here?
Thank you in advance!
Make GRService_DownloadStringCompleted method non static:
void GRService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
List<Area> dataList = new List<Area>();
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(dataList.GetType());
dataList = ser.ReadObject(memoryStream) as List<Area>;
memoryStream.Close();
RoomAreas.ItemSource = dataList;
}
Try adding ItemsSource="{Binding}" to the combobox property within the Xaml
Related
This question already has answers here:
Why does WPF support binding to properties of an object, but not fields?
(2 answers)
Closed last month.
I am still a beginner and I'm trying to make a application where a user gets to choose a file. For that I use OpenFileDialog, which has worked fine for me in the past. The file path and content should then be each displayed in a separate textbox. I tried to achieve this by storing the content and path in two strings. Because I want to use those strings later on in my project in another .cs file I figured I make them globally accessable by defining them as public string content = "No file selected yet;. The "No file selected yet" should be the default text before the user has selected anything.
I searched online and tried to accomplish my goals by using DataContext and Binding, but I can't figure out how to make it work. This is the code I have right now:
xaml file:
<UserControl x:Class="Project_Neon.MVVM.View.ChooseFileView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Project_Neon.MVVM.View"
mc:Ignorable="d"
d:DesignHeight="423.4"
d:DesignWidth="548.4">
<StackPanel Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="70"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="100"/>
<RowDefinition Height="35"/>
<RowDefinition Height="218.4"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="1"
Grid.ColumnSpan="2"
Margin="0,5,20,0"
Text="Choose File"
Foreground="Black"
FontSize="28"
FontFamily="/Fonts/#Kanit Semi"/>
<TextBlock Text="Select the text document with the cheat sheet.
Only Documents in a .txt format can be accepted."
Foreground="Black"
FontSize="22"
FontFamily="/Fonts/#Kanit Light"
Grid.Row="1"
Grid.Column="1"
Grid.ColumnSpan="2"
Margin="0,0,20,10"/>
<Button Grid.Row="2"
Grid.Column="1"
VerticalAlignment="Top"
Content="Select file"
Height="25"
Width="70"
FontFamily="/Fonts/#Kanit"
FontSize="14"
Style="{StaticResource SelectFileButtonTheme}"
Click="SelectFileButton_Click"/>
<Grid Grid.Row="2"
Grid.Column="2"
Height="25"
VerticalAlignment="Top"
Margin="0,0,20,0">
<Border Padding="10"
BorderBrush="#1f1f1f"
BorderThickness="1">
</Border>
<TextBlock Name="FilePathDisplay"
Text="{Binding Path=CheatFilePath}"
VerticalAlignment="Center"
Margin="5,0,0,0"
FontSize="14"
FontFamily="/Fonts/#Kanit Light"/>
</Grid>
<Grid Grid.Row="3"
Grid.Column="1"
Grid.ColumnSpan="2"
Margin="0,0,20,20">
<TextBlock Height="20"
VerticalAlignment="Top"
Background="#1f1f1f"
Foreground="White"
Text=" Preview:"
FontSize="14"
FontFamily="/Fonts/#Kanit"/>
<Border Padding="10"
BorderBrush="#1f1f1f"
BorderThickness="1"
Margin="0,20,0,0">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" Margin="-10,-10,-10,-10">
<TextBlock Width="Auto"
TextWrapping="Wrap"
Text="{Binding Path=CheatFileContent}"
VerticalAlignment="Top"
FontSize="13"
Margin="1.5,0,1.5,0"
FontFamily="/Fonts/#Kanit Light"/>
</ScrollViewer>
</Border>
</Grid>
</Grid>
</StackPanel>
</UserControl>
and the xaml.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Project_Neon.MVVM.View
{
/// <summary>
/// Interaction logic for ChooseFileView.xaml
/// </summary>
public partial class ChooseFileView : System.Windows.Controls.UserControl
{
public ChooseFileView()
{
InitializeComponent();
this.DataContext = this;
}
public string CheatFileContent = "No file selected yet";
public string CheatFilePath = "No file selected yet";
private void SelectFileButton_Click(object sender, RoutedEventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = ".txt (*.txt)|*.txt";
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var CheatFileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(CheatFileStream))
{
CheatFileContent = reader.ReadToEnd();
CheatFilePath = openFileDialog.FileName;
OnPropertyChanged(nameof(CheatFilePath));
OnPropertyChanged(nameof(CheatFileContent));
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I'm afraid that maybe my strings aren't defined right.
(I deleted most of the code from my previous attempts of actually binding the data, because I only got errors.)
As #Andy pointed out you need to bind to properties not fields (check #Marc Gravell answer)
I included the raising of the event inside the setter as it makes more sense
ChooseFileView.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Project_Neon.MVVM.View
{
/// <summary>
/// Interaction logic for ChooseFileView.xaml
/// </summary>
public partial class ChooseFileView : System.Windows.Controls.UserControl, System.ComponentModel.INotifyPropertyChanged
{
private string _cheatFileContent;
private string _cheatFilePath;
public event PropertyChangedEventHandler? PropertyChanged;
public string CheatFileContent
{
get => _cheatFileContent;
set
{
if (_cheatFileContent != value)
{
_cheatFileContent = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CheatFileContent)));
}
}
}
public string CheatFilePath
{
get => _cheatFilePath;
set
{
if (_cheatFilePath != value)
{
_cheatFilePath = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CheatFilePath)));
}
}
}
public ChooseFileView()
{
InitializeComponent();
this.DataContext = this;
CheatFileContent = "No file selected yet";
CheatFilePath = "No file selected yet";
}
private void SelectFileButton_Click(object sender, RoutedEventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = ".txt (*.txt)|*.txt";
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var CheatFileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(CheatFileStream))
{
CheatFileContent = reader.ReadToEnd();
CheatFilePath = openFileDialog.FileName;
}
}
}
}
}
}
I'm making an image viewer. I have a mouse event that is supposed to trigger when an image (or child of StackPanel in this case), is clicked. The event is triggered as intended. The problem is, since the pathfile of the images is different depending on whichever is selected (in which directory, etc.), I just don't know how to get the pathfile of the specific image that is currently clicked on. The directory depends on whichever folder is loaded, so the pathfile could be different everytime.
If you scroll all the way down to Image_Load(), I have the Pic.Fill which is a reference to the rectangle that is being filled with the image. I'm trying to find the first parameter for Uri(_,_), which is supposed to be where the #"path" of the current image is.
using System;
using System.IO;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Drawing;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
List<string> paths = new List<string>();
string[] extension = new[] { ".jpg", ".png", ".jpeg", ".gif", ".bmp", ".tif", ".tiff" };
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) {
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(fbd.SelectedPath);
FileLocation.Text = fbd.SelectedPath;
}
}
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
LoadPhotos();
}
private void LoadPhotos()
{
try
{
DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);
foreach (var fi in di.GetFiles().Where(f => extension.Contains(f.Extension.ToLower())).ToArray())
{
paths.Add(fi.FullName);
}
Photos.ItemsSource = paths;
} catch (Exception e)
{
Console.WriteLine("File not found.", e.Source);
}
}
private void Image_Load(object sender, MouseButtonEventArgs e)
{
// What is the reference here?
Pic.Fill = new ImageBrush { ImageSource = new BitmapImage(new Uri(/*Insert pathfile here*/, UriKind.Absolute)) };
}
}
}
Here's my .xaml. I've analyzed it to see a reference but the only thing that stands out is the Image Source, which I've tagged with a comment. It's set to { Binding . } which I'm going to assume means, whatever image is referenced. But how do I connect that variable reference to my Image_Load()? (which is declared on the instantiation of ListBox)
<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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="1081" Width="1720.5">
<Grid Margin="0,0,2,-0.578">
<Button x:Name="OpenButton" Content="Load" HorizontalAlignment="Left" Height="44" Margin="1166.374,932.042,0,0" VerticalAlignment="Top" Width="145.666" Background="#FFDDDDDD" FontSize="24" Click="OpenButton_Click"/>
<Button x:Name="BrowseButton" Content="Browse" HorizontalAlignment="Left" Height="44" Margin="58.666,932.042,0,0" VerticalAlignment="Top" Width="134.166" Background="#FFDDDDDD" FontSize="24" Click="Button_Click"/>
<Rectangle x:Name="Pic" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="878.767" Margin="58.666,34.733,0,0" Stroke="Black" VerticalAlignment="Top" Width="1253.374"/>
<ScrollViewer VerticalScrollBarVisibility="Visible" Width="327.46" HorizontalAlignment="Left" Margin="1339.04,34.733,0,137.078" RenderTransformOrigin="0.5,0.5" >
<StackPanel Width="327.46" RenderTransformOrigin="0.516,0.496" HorizontalAlignment="Left" VerticalAlignment="Center" Height="878.085">
<ListBox x:Name="Photos"
Grid.Row="2" Grid.Column="1" Height="876" PreviewMouseDown="Image_Load">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="300" Height="100">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
/* Image Source? */
<Image Source="{Binding .}" Grid.Column="0"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</ScrollViewer>
<TextBlock x:Name="FileLocation" HorizontalAlignment="Left" Height="44" Margin="192.832,948.542,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="973.542" Foreground="#FF515151" TextAlignment="Center" FontSize="14"/>
</Grid>
</Window>
I've been learning on the way using Blend-- some youtube tutorials here and there. I've tried to look for a solution online but all the questions about it usually involve a static and specific directory. This is my first program and the only thing I need is that darn path file reference. There are so many object reference so I just don't even know how to wrap my head around it, being so unfamiliar with these classes. Some assistance would be very much appreciated! :)
I have tried looking at questions similar to this for an answer but they seem to differ slightly, mind is 'RoutedEventHandler' while other questions are about just 'eventhandler' and don't really seem to match with my problem.
To help you understand, Im making a basic wpf c# TCP client that sends a message (what is in a textbox) while reading off the stream for a message back, then placing it into a text file.
This error occurs when trying to compile.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace client
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// Ip and port variables used for connect and gui display
string ipaddress = "127.0.0.1";
int port = 8888;
/// <summary>
/// Set new TCP client, stream writer and reader, connect and gui show ip and port
/// </summary>
public void MainWindow_Connect(object sender, EventArgs e)
{
TcpClient client = new TcpClient(); // New TcpClient
client.Connect(ipaddress, port); // IP, Port to connect
StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
// Interface label show ip and port
serverip_lbl.Content = ipaddress;
portno_lbl.Content = port;
}
/// <summary>
/// Send message inside message_txt textbox, write to network stream and send
/// </summary>
private void send_button_Click(object sender, RoutedEventArgs e, StreamWriter sw)
{
sw.WriteLine(message_txt.Text);
sw.Flush();
}
/// <summary>
/// Read from message from the server, write to textfile
/// </summary>
public void serverStream(StreamReader sr)
{
// Create a string array
string[] message = { "\n", sr.ReadToEnd() };
// WriteAllLines creates a file, writes a collection of strings to the file and then closes the file
File.WriteAllLines(#"C:\Users\Public\Documents\Messages.txt", message);
}
}
}
XAML:
<Window x:Class="client.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:client"
Loaded = "MainWindow_Connect"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="400">
<Grid>
<Label x:Name="titleclient_txt" Content="Client" Margin="10,10,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18.667" HorizontalAlignment="Left" FontStyle="Italic" d:IsLocked="True"/>
<Label x:Name="demotitle_txt" Content="Sending a message" HorizontalAlignment="Right" Margin="0,50,87,0" VerticalAlignment="Top" FontSize="24" FontWeight="Bold" d:IsLocked="True"/>
<Label x:Name="server_lbl" Content="Server IP:" HorizontalAlignment="Left" Margin="74,106,0,0" VerticalAlignment="Top" d:IsLocked="True"/>
<Label x:Name="serverip_lbl" Content="" HorizontalAlignment="Left" Margin="155,106,0,0" VerticalAlignment="Top" Width="150" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
<Label x:Name="port_lbl" Content="Port:" HorizontalAlignment="Left" Margin="74,146,0,0" VerticalAlignment="Top" d:IsLocked="True"/>
<Label x:Name="portno_lbl" Content="" HorizontalAlignment="Left" Margin="155,146,0,0" VerticalAlignment="Top" Width="150" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>
<Label x:Name="message_lbl" Content="Message:" HorizontalAlignment="Left" Margin="74,199,0,0" VerticalAlignment="Top" d:IsLocked="True"/>
<TextBox x:Name="message_txt" HorizontalAlignment="Left" Height="70" Margin="74,230,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="250"/>
<Button x:Name="send_button" Content="Send" HorizontalAlignment="Left" Margin="155,344,0,0" VerticalAlignment="Top" Width="75" Click="send_button_Click"/>
</Grid>
Your send_button_Click method must have the same signature as the RoutedEventHandler. But yours has an additional StreamWriter argument which must be removed.
So I'm trying to work a very simple dice app on a XAML document using Visual Studio 2012, but I can't figure out what to do with the error. I've tried adding using bitmapimage; but it still won't work.
Here are the errors I'm getting:
Error 1 Undefined namespace. The 'using' URI refers to a namespace 'DiceRoll' that could not be found.
Error 2 The type or namespace name 'BitmapImage' could not be found (are you missing a using directive or an assembly reference?)
CS:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using BitmapImage;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace DiceRoll
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainPage : Page
{
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Random num = new Random();
int Number = num.Next(1, 7);
BitmapImage Img = new BitmapImage(new Uri(#"DiceFaces\" + Number.ToString() + ".bmp", UriKind.Relative));
textBlock1.Text = Number.ToString() + " Number";
image1.Source = Img;
}
}
}
XAML:
<Page
x:Class="DiceRoll.MainPage"
IsTabStop="false"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DiceRoll"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<TextBlock Height="56" HorizontalAlignment="Left" Margin="275,134,0,0" Name="textBlock1" VerticalAlignment="Top" Width="182" />
<Button Content="Roll a Dice" Height="23" HorizontalAlignment="Left" Margin="194,151,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<Image Height="72" HorizontalAlignment="Left" Margin="195,56,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="74" />
</Grid>
</Page>
Try
using System.Windows.Media.Imaging.BitmapImage;
Instead of
using BitmapImage;
An easier way is to let Visual Studio do it for you :
Right click on BitmapImage in your code -> resolve, and select the right namespace (there is generaly only one)
For the xaml, let Visual studio do it for you too, or :
<Page ...
xmlns:local="clr-namespace:System.Windows;assembly=DiceRoll"
/>
I'm using ImageTools for Silverlight to load a JPG image, but the decoded image quality is BAD (no anti-aliasing, see the second image in the red square).
Here is my code:
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == true)
{
var stream = dlg.File.OpenRead();
var newImg = new ExtendedImage(); // ExtendedImage is a ImageTools Api class
var d= new ImageTools.IO.Jpeg.JpegDecoder();
d.Decode(newImg, stream);
image1.Source = newImg.ToBitmap(); //image1 is a System.Windows.Controls.Image
}
Source image
Bad result
Observations
If I set image1.source directly to a URL from the original image, the image is rendered correctly!
Is this a bug in the ImageTools API?
The problem is posted on Codeplex, but it doesn't have any answers.
If I rewrite my code, I get the same result.
XAML
<UserControl x:Class="JPGDecoder.MainPage"
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">
<Grid x:Name="LayoutRoot" Background="White">
<Image Height="120" HorizontalAlignment="Left" Margin="46,75,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="160" Source="/JPGDecoder;component/Images/org.jpg" />
<Image Height="120" HorizontalAlignment="Left" Margin="212,75,0,0" Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="160" />
<Button Content="Decode JPG from File Stream" Height="23" HorizontalAlignment="Left" Margin="44,25,0,0" Name="button1" VerticalAlignment="Top" Width="192" Click="button1_Click" />
</Grid>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ImageTools;
namespace JPGDecoder
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
if (dlg.ShowDialog()==true)
{
var stream = dlg.File.OpenRead();
var newImg = new ExtendedImage();
var d = new ImageTools.IO.Jpeg.JpegDecoder();
d.Decode(newImg, stream);
image2.Source = newImg.ToBitmap();
}
}
}
}
Result
Mmm... I think it would be a good idea if you post a question to the ImageTool codeplex forum, this author used to answer quite fast.
Have you checked the samples from his site?
Usually I had no problems with this library.
Cheers
Braulio
ImageTools does not support antialising, so I got FJCore from Subversion and ran the sample app.
First test same result, bad quality.
Looking at the source code, I found this code block:
// Resize
DecodedJpeg jpegOut = new DecodedJpeg(
new ImageResizer(jpegIn.Image).Resize(320, ResamplingFilters.NearestNeighbor),
jpegIn.MetaHeaders); // Retain EXIF details
and changed it to this:
//Resize
DecodedJpeg jpegOut = new DecodedJpeg(
new ImageResizer(jpegIn.Image).Resize(320, ResamplingFilters.LowpassAntiAlias),
jpegIn.MetaHeaders); // Retain EXIF details
This is the solution: ResamplingFilters.LowpassAntiAlias
Thanks everyone!!