I have a wpf application with two panes similar to powerpoint application:
left pane which shows list of all the panels in listbox
right pane which shows the selected panel
In the listbox I want to display panel as thumbnail and update the thumbnail as an when new controls are added to panel in right pane.
Just like powerpoint application thumbnail behaviour.
By using RenderTargetBitmap and PngBitmapEncoder we can capture a region of window.
and by using the PngBitmapEncoder frame Property assigned it to Image Source.
Lets start with Xaml
I divided the window by two half and left and right panel. Same in PowerPoint with less style. In order to demonstrate I have implemented to add TextBox on the right panel and the preview will be displayed on the left panel thumbnail.
<Grid Background="Aqua" x:Name="gridg">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox HorizontalAlignment="Left" Height="372" Margin="10,38,0,0" VerticalAlignment="Top" Width="306" Grid.Column="0" x:Name="Listtems" SelectionChanged="Listtems_SelectionChanged" />
<Button Content="+ TextBox" HorizontalAlignment="Left" Margin="142,10,0,0" VerticalAlignment="Top" Width="174" Click="Button_Click" Grid.Column="0"/>
<StackPanel x:Name="stackPanel" Background="Wheat" Grid.ColumnSpan="2" Margin="321,0,0,0" />
</Grid>
As soon as you click on the left panel item, the corresponding the control will be displayed on the right panel with the data.
In order to keep track of the items in the ListBox, I have used Dictionary with ItemIndex and to it's corresponding item's index used control.
Window's Code Behind
/// <summary>
/// Interaction logic for Window6.xaml
/// </summary>
public partial class Window6 : Window
{
Dictionary<int, Control> _dictionaryControls = new Dictionary<int, Control>();
DispatcherTimer dispatcherTimer = new DispatcherTimer();
public Window6()
{
InitializeComponent();
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Start();
}
private void BmpImage()
{
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(800, 450, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(stackPanel);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
Image img = new Image();
img.Source = pngImage.Frames[0];
img.Height = 148;
img.Width = 222;
Listtems.Items.Add(img);
Listtems.SelectedIndex = Listtems.Items.Count - 1;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
stackPanel.Children.Clear();
int item = Listtems.Items.Count;
TextBox txtControl = new TextBox();
txtControl.FontSize = 100;
txtControl.Height = 122;
txtControl.TextWrapping = TextWrapping.Wrap;
_dictionaryControls.Add(item, txtControl);
stackPanel.Children.Add(txtControl);
stackPanel.UpdateLayout();
BmpImage();
}
private void Listtems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateThumbNail();
}
private void UpdateThumbNail()
{
int indexbackup = -1;
Listtems.SelectionChanged -= Listtems_SelectionChanged;
Control control;
_dictionaryControls.TryGetValue(Listtems.SelectedIndex, out control);
if (control == null)
{
Listtems.SelectionChanged += Listtems_SelectionChanged;
return;
}
indexbackup = Listtems.SelectedIndex;
stackPanel.Children.Clear();
stackPanel.Children.Add(control);
stackPanel.UpdateLayout();
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(800, 450, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(stackPanel);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
Image img = new Image();
img.Source = pngImage.Frames[0];
img.Height = 148;
img.Width = 222;
Listtems.Items.Insert(Listtems.SelectedIndex, img);
Listtems.Items.RemoveAt(Listtems.SelectedIndex);
Listtems.SelectedIndex = indexbackup;
Listtems.SelectionChanged += Listtems_SelectionChanged;
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
UpdateThumbNail();
}
}
BmpImage() : - I used to capture or in other words the print screen of the StackPanel control.
Button_Click Event :- Is used to create a new Item in ListBox adding Image with the current print screen of the TextBox Control in StackPanel. It also adds control in _dictionaryControls variable.
Listtems_SelectionChanged Event:- Clears the StackPanel and then take the TextBox Control from _dictionaryControls based on the SelectedIndex of ListBox and place it in the StackPanel by taking current snapshot of the StackPanel.
For Demo Purpose, I have done it only for TextBox Control, but you can do it for any other control with a little tweaking.
UpdateThumbNail created a method responsible to update the image in Listbox based on the ListBoxItem.
dispatcherTimer_Tick : - Event is responsible to call the UpdateThumbNail() Method for every second.
Related
I'm trying to create a snapshot/image/bitmap of an element that I can display as content in another control.
It seems the suggested way to do this is with a VisualBrush, but I can't seem to get it to create a snapshot of the current value and keep that state. When you alter the original source, the changes are applied to all the "copies" that have been made too.
I have made a simple example to show what I mean.
What I want is for the items added to the stackpanel to have the opacity that was set when they were cloned. But instead, changing the opacity on the source changes all "clones".
<StackPanel Width="200" x:Name="sp">
<DockPanel>
<Button Content="Clone"
Click="OnCloneButtonClick" />
<TextBlock Text="Value" x:Name="tb" Background="Red" />
</DockPanel>
</StackPanel>
private void OnCloneButtonClick(object sender, RoutedEventArgs e)
{
tb.Opacity -= 0.1;
var brush = new VisualBrush(tb).CloneCurrentValue();
sp.Children.Add(new Border() { Background = brush, Width = tb.ActualWidth, Height = tb.ActualHeight });
}
I am afraid the visual elements aren't cloned when you call CloneCurrentValue().
You will have to clone the element yourself, for example by serializing the element to XAML and then deserialize it back using the XamlWriter.Save and XamlReader.Parse methods respectively:
private void OnCloneButtonClick(object sender, RoutedEventArgs e)
{
tb.Opacity -= 0.1;
var brush = new VisualBrush(Clone(tb));
sp.Children.Add(new Border() { Background = brush, Width = tb.ActualWidth, Height = tb.ActualHeight });
}
private static Visual Clone(Visual visual)
{
string xaml = XamlWriter.Save(visual);
return (Visual)XamlReader.Parse(xaml);
}
I need that if my pop up window appear (after click) , the main window brightness has to decrease, maybe someone know how to do it?
Example:
EDIT: I create canvas, but do not know how to use it, brightness need decrease then pop up appear.
code:
private void sample_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string path1 = System.AppDomain.CurrentDomain.BaseDirectory + "../../loader_bg.png";
string path2 = System.AppDomain.CurrentDomain.BaseDirectory + "../../loader.gif";
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(
new Uri(path1));
myBrush.ImageSource = image.Source;
Image ima = new Image();
MediaElement gif = new MediaElement();
ima.Source = new BitmapImage(new Uri(path1));
gif.Source=new Uri(path2);
gif.Height = 72;
gif.Width = 72;
var pop = new Popup
{
IsOpen = true,
StaysOpen = false,
AllowsTransparency = true,
VerticalOffset = 350,
HorizontalOffset = 700,
Height = 128,
Width = 128,
};
Canvas c=new Canvas();
c.Background=Brushes.Black;
c.Opacity = 0.6;
Grid p = new Grid();
p.Background = myBrush;
//p.Children.Add(ima);
//p.Children.Add(c);
p.Children.Add(gif);
pop.Child = p;
}
}
EDIT 2:
I have the same question only my code is change. Now I created new xaml.cs for pop up window, and try to achieve the same purpose, but I do not get the same (I talk about brightness decrease).
Its my new xaml.cs :
namespace uploader
{
/// <summary>
/// Interaction logic for PopupPanel.xaml
/// </summary>
public partial class PopupPanel : UserControl
{
private Popup _currentPopup;
public PopupPanel()
{
InitializeComponent();
string path1 = System.AppDomain.CurrentDomain.BaseDirectory + "../../loader_bg.png";
string path2 = System.AppDomain.CurrentDomain.BaseDirectory + "../../loader.gif";
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(new Uri(path1));
myBrush.ImageSource = image.Source;
MediaElement gif = new MediaElement();
gif.Source=new Uri(path2);
gif.Height = 72;
gif.Width = 72;
_currentPopup = new Popup
{
StaysOpen = false,
AllowsTransparency = true,
VerticalOffset = 350,
HorizontalOffset = 700,
Height = 128,
Width = 128,
};
Overlay.Visibility = Visibility.Visible;
_currentPopup.Closed += PopupClosing;
_currentPopup.IsOpen = true;
Grid p = new Grid();
p.Background = myBrush;
p.Children.Add(gif);
_currentPopup.Child = p;
}
private void PopupClosing(object sender, EventArgs e)
{
_currentPopup.Closed -= PopupClosing;
_currentPopup = null;
Overlay.Visibility = Visibility.Collapsed;
}
}
}
My Mainwindow.xaml.cs:
namespace uploader
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void sample_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
PopupPanel pop = new PopupPanel();
}
...
I do this in all my WPF applications by using a Canvas with black background and opacity
Example:
<Window>
<Grid>
<!--Main content-->
<UserControl/>
<Grid>
<Canvas Background="Black" Opacity="0.6"/>
<!--Overlay content-->
<UserControl VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</Grid>
</Window>
Using your current code, you will need to handle the visibility of the Canvas overlay.
It's easier to to have it defined within your XAML as shown below:
<Window>
<Grid>
<!--Main content-->
<UserControl/>
<Grid>
<Canvas x:Name="Overlay"
Background="Black"
Opacity="0.6"
Visibility="Collapsed"/>
<!--Overlay content-->
<UserControl VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</Grid>
</Window>
Then, in your code-behind you can set the visibility before the popup opens, and when it closes:
Popup _currentPopup;
private void sample_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
...
_currentPopup = new Popup
{
StaysOpen = false,
AllowsTransparency = true,
VerticalOffset = 350,
HorizontalOffset = 700,
Height = 128,
Width = 128
};
Overlay.Visibility = Visibility.Visible;
_currentPopup.Closed += PopupClosing;
_currentPopup.IsOpen = true;
}
private void PopupClosing(object sender, EventArgs e)
{
_currentPopup.Closed -= PopupClosing;
_currentPopup = null;
Overlay.Visibility = Visibility.Collapsed;
}
Note, that I am using a local variable to keep a reference to the popup. This is so that I can un-subscribe from the Closing event (helps prevent memory leaks)
I have large treeview full of textboxes, each with tooltip containing a unique image. The image is stored in a property as a bytearray and I bind to it. Every time a new tooltip is displayed more memory is used.
I will be scaling the image, but that doesn't address the root of the problem. If there a way to free the memory used after the tooltip is no longer displayed?
<TextBlock.ToolTip>
<StackPanel>
<Image MaxWidth="650"
MaxHeight="400"
Source="{Binding ImageAsByteArray}"/>
<TextBlock Text="{Binding FilePath, StringFormat='Full Path: {0}'}" />
</StackPanel>
</TextBlock.ToolTip>
The tooltip can be set to any framework element, so could dynamically create this as an object behind the scenes:
<TextBlock ToolTip={Binding ToolTip} />
Then your view model or code behind could dynamically create this object and handle the loaded/unloaded event to capture when the tooltip displays.
I've done it below with a canvas is case you want to add other children besides the image:
var tooltipCanvas = new Canvas();
var img = new Image();
tooltipCanvas.Children.Add(img);
tooltipCanvas.Width = 500;
tooltipCanvas.Height = 500;
tooltipCanvas.Loaded += Tooltip_Loaded;
tooltipCanvas.Unloaded += Tooltip_Unloaded;
Then you could populate the image source just for the time the image is shown using the loaded and unloaded event handlers:
private void Tooltip_Loaded(object sender, RoutedEventArgs e)
{
var canvas = sender as Canvas;
var img = canvas.Children[0] as Image;
img.Source = /* get your image bytes */;
}
private void Tooltip_Unloaded(object sender, RoutedEventArgs e)
{
var canvas = sender as Canvas;
var img = canvas.Children[0] as Image;
img.Source = null;
}
This is going to be straight forward no doubt, but for what ever reason, my mind is drawing a blank on it.
I've got a small, non-resizeable window (325x450) which has 3 Expanders in it, stacked vertically. Each Expander contains an ItemsControl that can potentially have a lot of items in and therefore need to scroll.
What I can't seem to get right is how to layout the Expanders so that they expand to fill any space that is available without pushing other elements off the screen. I can sort of achieve what I'm after by using a Grid and putting each expander in a row with a * height, but this means they are always taking up 1/3 of the window each which defeats the point of the Expander :)
Crappy diagram of what I'm trying to achieve:
This requirement is a little unusal because the you want the state of the Children in the Grid to decide the Height of the RowDefinition they are in.
I really like the layout idea though and I can't believe I never had a similar requirement myself.. :)
For a reusable solution I would use an Attached Behavior for the Grid.
The behavior will subscribe to the Attached Events Expander.Expanded and Expander.Collapsed and in the event handlers, get the right RowDefinition from Grid.GetRow and update the Height accordingly. It works like this
<Grid ex:GridExpanderSizeBehavior.SizeRowsToExpanderState="True">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Expander Grid.Row="0" ... />
<Expander Grid.Row="1" ... />
<Expander Grid.Row="2" ... />
<!-- ... -->
</Grid>
And here is GridExpanderSizeBehavior
public class GridExpanderSizeBehavior
{
public static DependencyProperty SizeRowsToExpanderStateProperty =
DependencyProperty.RegisterAttached("SizeRowsToExpanderState",
typeof(bool),
typeof(GridExpanderSizeBehavior),
new FrameworkPropertyMetadata(false, SizeRowsToExpanderStateChanged));
public static void SetSizeRowsToExpanderState(Grid grid, bool value)
{
grid.SetValue(SizeRowsToExpanderStateProperty, value);
}
private static void SizeRowsToExpanderStateChanged(object target, DependencyPropertyChangedEventArgs e)
{
Grid grid = target as Grid;
if (grid != null)
{
if ((bool)e.NewValue == true)
{
grid.AddHandler(Expander.ExpandedEvent, new RoutedEventHandler(Expander_Expanded));
grid.AddHandler(Expander.CollapsedEvent, new RoutedEventHandler(Expander_Collapsed));
}
else if ((bool)e.OldValue == true)
{
grid.RemoveHandler(Expander.ExpandedEvent, new RoutedEventHandler(Expander_Expanded));
grid.RemoveHandler(Expander.CollapsedEvent, new RoutedEventHandler(Expander_Collapsed));
}
}
}
private static void Expander_Expanded(object sender, RoutedEventArgs e)
{
Grid grid = sender as Grid;
Expander expander = e.OriginalSource as Expander;
int row = Grid.GetRow(expander);
if (row <= grid.RowDefinitions.Count)
{
grid.RowDefinitions[row].Height = new GridLength(1.0, GridUnitType.Star);
}
}
private static void Expander_Collapsed(object sender, RoutedEventArgs e)
{
Grid grid = sender as Grid;
Expander expander = e.OriginalSource as Expander;
int row = Grid.GetRow(expander);
if (row <= grid.RowDefinitions.Count)
{
grid.RowDefinitions[row].Height = new GridLength(1.0, GridUnitType.Auto);
}
}
}
If you don't mind a little code-behind, you could probably hook into the Expanded/Collapsed events, find the parent Grid, get the RowDefinition for the expander, and set the value equal to * if its expanded, or Auto if not.
For example,
Expander ex = sender as Expander;
Grid parent = FindAncestor<Grid>(ex);
int rowIndex = Grid.GetRow(ex);
if (parent.RowDefinitions.Count > rowIndex && rowIndex >= 0)
parent.RowDefinitions[rowIndex].Height =
(ex.IsExpanded ? new GridLength(1, GridUnitType.Star) : GridLength.Auto);
And the FindAncestor method is defined as this:
public static T FindAncestor<T>(DependencyObject current)
where T : DependencyObject
{
// Need this call to avoid returning current object if it is the
// same type as parent we are looking for
current = VisualTreeHelper.GetParent(current);
while (current != null)
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
};
return null;
}
I am animating a TextBlock. In 60 seconds, it increases FontSize from 8pt to 200pt. Everything is working fine, except that my animation is moving up and down a bit as the text grows. Why is this happening and is it possible to avoid this?
I have a very simple XAML file:
<Window x:Class="Timer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="800"
Height="500"
Title="MainWindow"
Loaded="Window_Loaded">
<Grid>
<TextBlock
Name="TimerTextBlock"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="00h : 00m : 00.000s" />
</Grid>
</Window>
And equally simple code-behind:
public partial class MainWindow : Window
{
private const string timerFormat = "{0:hh'h : 'mm'm : 'ss'.'fff's'}";
private DispatcherTimer dispatcherTimer;
private DateTime targetTime;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
targetTime = DateTime.Now.AddSeconds(60);
double totalTime = targetTime.Subtract(DateTime.Now).TotalMilliseconds;
DoubleAnimation animation = new DoubleAnimation();
animation.From = TimerTextBlock.FontSize;
animation.To = 200;
animation.Duration = new Duration(targetTime.Subtract(DateTime.Now));
TimerTextBlock.BeginAnimation(TextBlock.FontSizeProperty, animation);
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1);
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (DateTime.Compare(targetTime, DateTime.Now) > 0)
{
TimerTextBlock.Text =
string.Format(timerFormat, targetTime.Subtract(DateTime.Now));
}
}
}
Thank you for all the clarifications.
Your vertical jumping problem is due to font rendering rounding. Specifically, WPF will avoid subpixel font height in order to enable font smoothing. One way to avoid this is to convert your text into a path geometry and then use a scale transform to animate it.
Here is an alternate version of your example without the jumping. The new XAML is:
<Grid>
<Path Name="Path" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
and the new code when you load the window:
SetText("");
var transform = new ScaleTransform(1, 1);
Path.LayoutTransform = transform;
var animationX = new DoubleAnimation(1, 10, new Duration(TimeSpan.FromSeconds(60)));
transform.BeginAnimation(ScaleTransform.ScaleXProperty, animationX);
var animationY = new DoubleAnimation(1, 10, new Duration(TimeSpan.FromSeconds(60)));
transform.BeginAnimation(ScaleTransform.ScaleYProperty, animationY);
and a new method to set the text that is anmiated:
private void SetText(string text)
{
var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Lucida Console"), 12, Brushes.Black);
Path.Data = formatted.BuildGeometry(new Point(0, 0));
Path.Fill = Brushes.Black;
}
and you have call SetText from your timer event handler.
Note that to avoid horizontal jumpiness, you have to use a fixed-length text string and a constant-width font.