make ScrollViewer resize when the MainWindow resizes - c#

This is an attempt to implement a read-only Linux text file (one byte newline sequence) viewer for Windows.
It presently has a ScrollViewer that will not resize when the WPF MainWindow is resized. How do I make the ScrollViewer size subservient to the MainWindow?
private void ScrollViewer1GotFocus(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg =
new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = null;
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
StreamReader streamReader = new StreamReader(filename,
System.Text.Encoding.ASCII);
string text = streamReader.ReadToEnd();
FlowDocument flowDocument = new FlowDocument();
flowDocument.TextAlignment = TextAlignment.Left;
flowDocument.FontFamily = new FontFamily("Lucida Console");
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(text);
flowDocument.Blocks.Add(paragraph);
FlowDocumentScrollViewer fdsv = new FlowDocumentScrollViewer();
fdsv.Document = flowDocument;
ScrollViewer1.Content = fdsv;
}
}
private void MainWindow1SizeChanged(object sender, SizeChangedEventArgs e)
{
}
The XAML:
<Window x:Name="MainWindow1" x:Class="ReadOnlyViewLinux1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ReadOnlyView" Height="256" Width="512" SizeChanged="MainWindow1SizeChanged">
<ScrollViewer x:Name="ScrollViewer1" HorizontalAlignment="Left" Height="236" Margin="10,10,0,-21" VerticalAlignment="Top" Width="492" GotFocus="ScrollViewer1GotFocus"/>

Simply Leave the ScrollViewer with no Height, Width, or Margin properties:
<Window>
<ScrollViewer/>
</Window>

Related

Changing content of button removes style WPF

Changing the content image of a button makes it ignore any previously defined layout properties.
What I suspect is the fact that upon changing this.Content in the Button click event, it modifies:
<Button>
Everything found between these tags.
</Button>
And as my Style is inside those tags, it overrides it.
Here is the code for record:
private void ChangeImageFile(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files|*.png;*.jpeg;*.tiff;*.gif;*.bmp;*.jpg";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
bool? ok = ofd.ShowDialog();
if(ok == true)
{
Image loaded = new Image();
loaded.Source = new BitmapImage(new Uri(ofd.FileName));
loaded.Height = 100;
this.Content = loaded;
}
}
 
<Button x:Name="BookCover" Click="ChangeImageFile">
<Button.Content>
<Image Source="Images/NewBook.png"/>
</Button.Content>
<Button.Style>
<Style TargetType="{x:Type Button}">
... LONG STYLE ...
</Style>
</Button.Style>
</Button>
When you're using this.Content, this refers to the current window and not to the button. You either need to access the button by Name or cast the sender.
By Name:
BookCover.Content = loaded;
Cast the sender:
Button btn = (sender as Button);
if(btn != null)
btn.Content = loaded;

Load images in Image Button

I am using below code to load image in my image button. But the Image is not loading in Button. However, I'm not receiving any kind of error.
XAML Code:
Image Name="imgPhoto" HorizontalAlignment="Left" Height="160" Margin="10,41,0,0" VerticalAlignment="Top" Width="164"/>
Button Content="Load" HorizontalAlignment="Left" Margin="191,67,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
Below is the code to load the Image in Image Button.
Button Click Event Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
if (dlg.ShowDialog() == true)
{
string selectedFileName = dlg.File.Name;
imgPhoto.Source = new BitmapImage(new Uri(selectedFileName, UriKind.Relative));
}
}
with OpenFIleDialog we don't have File.Name we have only FileName property which Gets or sets a string containing the file name selected in the file dialog box.
check the below code
OpenFileDialog objOpenFileDialog = new OpenFileDialog();
objOpenFileDialog.Filter = "Image Files(.jpg)|*.jpg;*.gif;*.png";
if (objOpenFileDialog.ShowDialog() == true)
{
imgPhoto.Source =new BitmapImage(new Uri(objOpenFileDialog.FileName));
}
The problem is here: UriKind.Relative.
If you're building URI from file name, picked up from system's file dialog, then it is absolute URI:
myImage.Source = new BitmapImage(new Uri(fileDialog.FileName));
In other words, you should treat full path (e.g., "c:\folder\filename.ext") as absolute URI.
Change imgPhoto.Source code as below
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
if (dlg.ShowDialog() == true)
{
string selectedFileName = dlg.FileName;
//imgPhoto.Source = new BitmapImage(new Uri(selectedFileName, UriKind.Relative));
imgPhoto.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(selectedFileName);
}
}

C# WPF Media Video Player doesn't start

I try to make a Media Player on WPF.
I made this yet :
public partial class MyMediaPlayer : Window
{
public MyMediaPlayer()
{
InitializeComponent();
//
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\"; // init
dlg.Filter = "All Files (*.*)|*.*"; // filter
dlg.RestoreDirectory = true;
// dialog window
if (dlg.ShowDialog() == true) // checked ?
{
string selectedFileName = dlg.FileName; // path of the media
MediaPlayer player = new MediaPlayer();
player.Open(new Uri(selectedFileName, UriKind.Relative));
VideoDrawing aVideoDrawing = new VideoDrawing();
aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
aVideoDrawing.Player = player; // play
// never play
player.Play();
}
}
}
And the XAML file :
<Window ... >
<Grid>
<MediaElement Margin="10,10,10,0 " Source="D:\test.avi"
Name="McMediaElement"
Width="450" Height="250" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill"
/>
</Grid>
</Window>
But, the video never start, and the window stay white.
Help please :)
ps : sorry for my bad english
MediaPlayer Class (msdn):
MediaPlayer is different from a MediaElement in that it is not a
control that can be added directly to the user interface (UI) of an
application. To display media loaded using MediaPlayer, a VideoDrawing
or DrawingContext must be used.
So if you want to use MediaPlayer you should use DrawingBrush class:
...
string selectedFileName = dlg.FileName;
MediaPlayer player = new MediaPlayer();
player.Open(new Uri(selectedFileName, UriKind.Relative));
VideoDrawing aVideoDrawing = new VideoDrawing();
aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
aVideoDrawing.Player = player;
player.Play();
DrawingBrush DBrush = new DrawingBrush(aVideoDrawing);
this.Background = DBrush;
...
In this solution you don't have to add MediaElement in XAML.
To play media in XAML only, use a MediaElement (msdn).
XAML:
<MediaElement Name="McMediaElement" Source="D:\test.avi"
LoadedBehavior="Play" UnloadedBehavior="Stop" Stretch="Fill"
Margin="10,10,10,0" Width="450" Height="250"
/>
Code-behind:
public MainWindow()
{
InitializeComponent();
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "All Files (*.*)|*.*"; // filter
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == true)
{
string selectedFileName = dlg.FileName;
McMediaElement.Source = new Uri(selectedFileName, UriKind.Absolute);
}
}

Save window of controls with runtime geneated controls and reload with as previous state

I created project with thee control buttons. AddButton creates runtime button controls and adds it in canvas1. When i right click on runtime generated controls new window pop ups. I want to save this window and reload it with same state as i leave. I use xml serialisation, it loads but click on that buttons does't work.
Here is my code:
private void AddButton_Click(object sender, RoutedEventArgs e)
{
Button b = new Button();
b.MinHeight = 23;
b.MinWidth = 73;
b.SetValue(Canvas.LeftProperty, e.GetPosition(this).X);
b.SetValue(Canvas.TopProperty, e.GetPosition(this).Y);
b.Content = i.ToString();
canvas1.Children.Add(b);
b.MouseRightButtonUp += new MouseButtonEventHandler(NewButton_Click);
}
private void NewButton_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ContextMenu pMenu = new ContextMenu();
MenuItem item1 = new MenuItem();
item1.Header = "Properties";
pMenu.Items.Add(item1);
btn.ContextMenu = pMenu;
item1.Click += new RoutedEventHandler(item1_Click);
}
private void item1_Click(object sender, EventArgs e)
{
MenuItem btn = (MenuItem)sender;
ControlProp c = new ControlProp();
c.ShowDialog();
}
private void Save_Click(object sender, RoutedEventArgs e)
{
StringBuilder outstr = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.NewLineOnAttributes = true;
XamlDesignerSerializationManager dsm = new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings));
dsm.XamlWriterMode = XamlWriterMode.Expression;
XamlWriter.Save(this.canvas1, dsm);
string savedControls = outstr.ToString();
//Show Dialog Box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "Xaml documents (.xaml)|*.xaml"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
File.WriteAllText(filename, savedControls);
}
}
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
//Open FileDialog
string filename;
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "Xaml documents (.xaml)|*.xaml"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
filename = dlg.FileName;
//Open Xaml
StreamReader sR = new StreamReader(filename);
string text = sR.ReadToEnd();
sR.Close();
StringReader stringReader = new StringReader(text);
XmlReader xmlReader = XmlReader.Create(stringReader);
Canvas wp = (Canvas)System.Windows.Markup.XamlReader.Load(xmlReader);
canvas1.Children.Clear(); // clear the existing children
foreach (FrameworkElement child in wp.Children) // and for each child in the WrapPanel we just loaded (wp)
{
canvas1.Children.Add(CloneFrameworkElement(child)); // clone the child and add it to our existing wrap panel
}
}
}
FrameworkElement CloneFrameworkElement(FrameworkElement originalElement)
{
string elementString = XamlWriter.Save(originalElement);
StringReader stringReader = new StringReader(elementString);
XmlReader xmlReader = XmlReader.Create(stringReader);
FrameworkElement clonedElement = (FrameworkElement)XamlReader.Load(xmlReader);
return clonedElement;
}
In short ,i want to save my project that user created at runtime and reopen it like mspaint with save project and open project facility.
You can use XamlWriter (MSDN)

How can I get a FlowDocument Hyperlink to launch browser and go to URL in a WPF app?

The following code in a WPF app creates a hyperlink that looks and acts like a hyperlink, but doesn't do anything when clicked.
What do I have to change so that when I click it, it opens the default browser and goes to the specified URL?
alt text http://www.deviantsart.com/upload/4fbnq2.png
XAML:
<Window x:Class="TestLink238492.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="10">
<ContentControl x:Name="MainArea"/>
</StackPanel>
</Window>
Code Behind:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace TestLink238492
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
FlowDocumentScrollViewer fdsv = new FlowDocumentScrollViewer();
FlowDocument doc = new FlowDocument();
fdsv.Document = doc;
fdsv.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
doc.PagePadding = new Thickness(0);
Paragraph paragraph = new Paragraph();
doc.Blocks.Add(paragraph);
Run run = new Run("this is flow document text and ");
paragraph.Inlines.Add(run);
Run run2 = new Run("this is a hyperlink");
Hyperlink hlink = new Hyperlink(run2);
hlink.NavigateUri = new Uri("http://www.google.com");
paragraph.Inlines.Add(hlink);
StackPanel sp = new StackPanel();
TextBlock tb = new TextBlock();
tb.Text = "this is textblock text";
sp.Children.Add(tb);
sp.Children.Add(fdsv);
MainArea.Content = sp;
}
}
}
I found the answer to this one, you have to add RequestNavigate and handle it yourself:
Run run2 = new Run("this is a hyperlink");
Hyperlink hlink = new Hyperlink(run2);
hlink.NavigateUri = new Uri("http://www.google.com");
hlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(hlink_RequestNavigate);
paragraph.Inlines.Add(hlink);
void hlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
Got the solutions for this Poma. The code section below should be added to your class where you need to do this. Or you can put it in a static class somewhere if you need to get to it from multiple files. I've tweaked it slightly for what I'm doing.
#region Activate Hyperlinks in the Rich Text box
//http://stackoverflow.com/questions/5465667/handle-all-hyperlinks-mouseenter-event-in-a-loaded-loose-flowdocument
void SubscribeToAllHyperlinks(FlowDocument flowDocument)
{
var hyperlinks = GetVisuals(flowDocument).OfType<Hyperlink>();
foreach (var link in hyperlinks)
link.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(link_RequestNavigate);
}
public static IEnumerable<DependencyObject> GetVisuals(DependencyObject root)
{
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
{
yield return child;
foreach (var descendants in GetVisuals(child))
yield return descendants;
}
}
void link_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
//http://stackoverflow.com/questions/2288999/how-can-i-get-a-flowdocument-hyperlink-to-launch-browser-and-go-to-url-in-a-wpf
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
#endregion Activate Hyperlinks in the Rich Text box
You'll call it in your code like this:
string xaml = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(this.itemControl.NotificationItem.Body, true);
FlowDocument flowDocument = XamlReader.Load(new XmlTextReader(new StringReader(xaml))) as FlowDocument;
SubscribeToAllHyperlinks(flowDocument);
bodyFlowDocument.Document = flowDocument;
All the HTMLConverter stuff can be found at: http://blogs.msdn.com/b/wpfsdk/archive/2006/05/25/606317.aspx
That's if you need to convert HTML to a Flow Document. Although, that's slightly out of the scope of this topic.

Categories