Accessing a control - Missing a using directive or assembly reference - c#

I am using WPF application in C# and I want at the beginning to draw a triangle.
This is the error that appears when I run the program:
'WpfApplication1.mainWindow' does not contain a definition for
'mainViewport' and no extension method for 'mainViewport' accepting a
first argument of type 'WpfApplication1.mainWindow' could be found.
(are you missing a using directive or an assembly reference?)
Here is my XAML page:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF 3D Chart" Height="455" Width="689">
<Grid>
<Viewport3D Name="mainViewport" ClipToBounds="True">
<Viewport3D.Camera>
<PerspectiveCamera
FarPlaneDistance="100"
LookDirection="-11,-10,-9"
UpDirection="0,1,0"
NearPlaneDistance="1"
Position="11,10,9"
FieldOfView="70" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight
Color="White"
Direction="-2,-3,-1" />
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</Grid>
</Window>
and this is my code: (the error appears on the last line of my code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Windows.Media.Media3D;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
System.Windows.Media.Media3D.Point3D point0 = new Point3D(-0.5, 0, 0);
System.Windows.Media.Media3D.Point3D point1 = new Point3D(0.5, 0.5, 0.3);
System.Windows.Media.Media3D.Point3D point2 = new Point3D(0, 0.5, 0);
System.Windows.Media.Media3D.MeshGeometry3D triangleMesh = new MeshGeometry3D();
triangleMesh.Positions.Add(point0);
triangleMesh.Positions.Add(point1);
triangleMesh.Positions.Add(point2);
int n0 = 0;
int n1 = 1;
int n2 = 2;
triangleMesh.TriangleIndices.Add(n0);
triangleMesh.TriangleIndices.Add(n1);
triangleMesh.TriangleIndices.Add(n2);
System.Windows.Media.Media3D.Vector3D norm = new Vector3D(0, 0, 1);
triangleMesh.Normals.Add(norm);
triangleMesh.Normals.Add(norm);
triangleMesh.Normals.Add(norm);
System.Windows.Media.Media3D.Material frontMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));
System.Windows.Media.Media3D.GeometryModel3D triangleModel = new GeometryModel3D(triangleMesh, frontMaterial);
triangleModel.Transform = new Transform3DGroup();
System.Windows.Media.Media3D.ModelVisual3D visualModel = new ModelVisual3D();
visualModel.Content = triangleModel;
this.mainViewport.Children.Add(visualModel); //here appears the error
}
}
}

You are refering to the Viewport in the constructor. At that moment in time the Viewport has not been created yet.
Use the Loaded event handler of the Window like this
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<Grid>
Do NOT leave the constructor empty! There is an important call in there! The InitializeComponent loads the UI of the Window.
As far as I can see you removed that call in your code and that causes the code to break as well. Use the Loaded handler, that is what is for.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}

Your XAML creates a class named WPFChart.Window1 while your code modifies a class called WpfApplication1.MainWindow. I don't know which one is right, but you need to change one of them so they match.

Related

Why does the button keep going out of bounds? (WPF Application)

I'm quite new to C# so expect faulty/lengthy code for no good reason.
So i was playing around with WPF Applications as i wanted to know how to make a button move when hovered over it- Which i managed to do but now it goes out of bounds?
XAML code:
<Window x:Class="Opdracht7.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:Opdracht7"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="klikmij" Content="Click me!" MouseEnter="onMouseEnter" Click="onMouseClick" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="-0.989,-0.519" Height="33" Width="68"/>
</Grid>
</Window>
C# code dump:
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 static System.Net.Mime.MediaTypeNames;
namespace Opdracht7
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void onMouseEnter(object sender, MouseEventArgs e)
{
Random rnd1 = new Random();
int value1 = rnd1.Next(0, 250);
int value2 = rnd1.Next(0, 250);
int value3 = rnd1.Next(0, 250);
int value4 = rnd1.Next(0, 250);
Debug.WriteLine(value1);
Debug.WriteLine(value2);
Debug.WriteLine(value3);
Debug.WriteLine(value4);
klikmij.Margin = new Thickness(value1,value2, value3, value4);
}
private void onMouseClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Congratulations! You won nothing!");
}
public MainWindow()
{
InitializeComponent();
}
}
}
I set random range from 0 to 250, because when i adjust it to the window's actual height 'n width it goes out of bounds even faster.
For some strange reason when it goes over 230-ish (could be lower) the button is gone until you enlargen the window size.
Did i overlook a vital piece 'o code?
EDIT:
https://gyazo.com/342b20fdbbcef2a4834ab95c37aaf30e <- gif of it happening
EDIT 2:
https://gyazo.com/f04e1d64f9880cd01aa53f9169954377 <- gif of resizing window
After playing a bit in the designer with different values, it looks like in Grid margins take precedence, and the button gets smaller to accomodate. In case when it disappears, it's calculated height just becomes 0.
Set width and height for the button manually, then change just the left and top margin, while setting rest to 0:
<Grid>
<Button Margin="250,250,0,0" Width="100" Height="100">TEST</Button>
</Grid>
Play with values in designer first to see what's happening when.
Better, do not use an element's Margin for layout. For absolute positioning, use a Canvas:
<Grid>
<Canvas>
<Button x:Name="klikmij" Content="Click me!"
MouseEnter="onMouseEnter" Click="onMouseClick"
Height="33" Width="68"/>
</Canvas>
</Grid>
with thic code behind:
private readonly Random rnd = new Random();
private void onMouseEnter(object sender, MouseEventArgs e)
{
Canvas.SetLeft(klikmij, rnd.Next(0, 250));
Canvas.SetTop(klikmij, rnd.Next(0, 250));
}

How to show dialog after new selecteditem is shown in comboBox in wpf?

For example:I have a comboBox which has three items:AAAAA,BBBBB,CCCCC.Now the selected item is AAAAA, when I select BBBBB, selection changed event is fired. I want combobox show the current selected item (which now is BBBBB),but when messagebox show ,combobox still show AAAAA,just like the screen-shot below:
This is not what I want,I want ComboBox show BBBBB,and then the messagebox is popup. I didn't find any way to solve this problem .Can anybody help me ? Thanks!
You can use the DropDownClosed event.
<Window x:Class="WpfApp.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:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ComboBox x:Name="cbItem" Height="20" Width="150" SelectionChanged="cbItem_SelectionChanged"></ComboBox>
</Grid>
</Window>
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;
namespace WpfApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
cbItem.Items.Add("AAAA");
cbItem.Items.Add("BBBB");
cbItem.Items.Add("CCCC");
}
private void cbItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cmb = sender as System.Windows.Controls.ComboBox;
var str = cmb.SelectedItem;
MessageBox.Show(str.ToString());
}
}
}
use selection changed event and get selected item from Combobox and print it

IronPython as Scripting language to C# WPF VS 2015

I'm having some trouble that I hope you can help with! I've being trying to update this grid.Width parameter in a while loop, in a sleep(500) step. But, when I hit run script on my program, the entire GUI stops. I already tried running the script on a different Thread and using BackgroundWorker, but still both ways they block my application GUI until the script is finished. Could you take a look in the following code please?
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.IO;
using System.Threading;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string script;
ScriptEngine engine;
ScriptScope scope;
Thread threadScript;
public MainWindow()
{
InitializeComponent();
engine = Python.CreateEngine();
scope = engine.CreateScope();
string variableName = "isto";
object gridMier = gridScript;
scope.SetVariable(variableName, gridMier);
}
public void rodarScript()
{
this.Dispatcher.Invoke((Action)(() =>
{
try
{
//PARTE PARA ADICIONAR BIBLIOTECAS BASICAS PARA DESENVOLVIMENTO COM OS SCRIPTS
script = #"#Reference the WPF assemblies
import clr
clr.AddReferenceByName(""PresentationFramework, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"")
clr.AddReferenceByName(""PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"")
import System.Windows
def getMyObject():
return isto
objeto = getMyObject()
#Atalhos de referencias para adicionar
Thickness = System.Windows.Thickness
from System.Threading.Thread import Sleep
Debug = System.Diagnostics.Debug";
script = script + "\n" + textBoxScript.Text;
var source = engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
//var compiled = source.Compile();
//var result = compiled.Execute(scope);
source.Execute(scope);
}
catch (Exception qualquerExcecaoEncontrada)
{
MessageBox.Show(qualquerExcecaoEncontrada.ToString(), "Scripting Test do Mier", MessageBoxButton.OK);
}
}));
}
private void buttonScript_Click(object sender, RoutedEventArgs e)
{
threadScript = new Thread(rodarScript);
threadScript.Start();
}
}
}
example of the code in IronPython (textBoxScript.Text)
for num in range(1,100):
objeto.Width = objeto.Width + 1
Sleep(500)
This simple code, running on a Thread, blocks my entire GUI for 50 seconds.
Any help would be appreciated!
Thanks,
Lucas.
Creating a seperate thread and then putting the complete content in Dispatcher.Invoke does not sence. Because you are then again sync with the ui thread (the howle time). You should only invoke those things, which needs to be (UI access). First remove that from rodarScript and only use it for script = script + "\n" + textBoxScript.Text;:
public void rodarScript()
{
try
{
//PARTE PARA ADICIONAR BIBLIOTECAS BASICAS PARA DESENVOLVIMENTO COM OS SCRIPTS
script = #"#...";
this.Dispatcher.Invoke((Action)(() =>
{
script = script + "\n" + textBoxScript.Text;
}));
var source = engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
//var compiled = source.Compile();
//var result = compiled.Execute(scope);
source.Execute(scope);
}
catch (Exception qualquerExcecaoEncontrada)
{
MessageBox.Show(qualquerExcecaoEncontrada.ToString(), "Scripting Test do Mier", MessageBoxButton.OK);
}
}
(Removed IP-Code).
Then add some simple method, which accepts an instance of PythonFunction and add it as a variable, like this:
public void ExecuteInUI(object obj)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
var op = engine.CreateOperations(scope);
op.Invoke(obj);
}));
}
Add as variable:
scope.SetVariable("execute_in_ui", new Action<object>(ExecuteInUI));
Then you have to chagne your Python code a little bit, because you only want to use BeginInvoke, when you access the ui:
def inc_width():
objeto.Width = objeto.Width + 1
for num in range(1,100):
execute_in_ui(inc_width)
Sleep(500)
So we are passing the function information of inc_width to c# and execute it from there in ExecuteInUI. Then complete code will look like this:
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.IO;
using System.Threading;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace AsyncIronPython
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string script;
ScriptEngine engine;
ScriptScope scope;
Thread threadScript;
public MainWindow()
{
InitializeComponent();
engine = Python.CreateEngine();
scope = engine.CreateScope();
string variableName = "isto";
object gridMier = gridScript;
scope.SetVariable(variableName, gridMier);
scope.SetVariable("execute_in_ui", new Action<object>(ExecuteInUI));
}
public void ExecuteInUI(object obj)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
var op = engine.CreateOperations(scope);
op.Invoke(obj);
}));
}
public void rodarScript()
{
try
{
//PARTE PARA ADICIONAR BIBLIOTECAS BASICAS PARA DESENVOLVIMENTO COM OS SCRIPTS
script = #"#Reference the WPF assemblies
import clr
clr.AddReferenceByName(""PresentationFramework, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"")
clr.AddReferenceByName(""PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"")
import System.Windows
def getMyObject():
return isto
objeto = getMyObject()
#Atalhos de referencias para adicionar
Thickness = System.Windows.Thickness
from System.Threading.Thread import Sleep
Debug = System.Diagnostics.Debug";
this.Dispatcher.Invoke((Action)(() =>
{
script = script + "\n" + textBoxScript.Text;
}));
var source = engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
//var compiled = source.Compile();
//var result = compiled.Execute(scope);
source.Execute(scope);
}
catch (Exception qualquerExcecaoEncontrada)
{
MessageBox.Show(qualquerExcecaoEncontrada.ToString(), "Scripting Test do Mier", MessageBoxButton.OK);
}
}
private void buttonScript_Click(object sender, RoutedEventArgs e)
{
threadScript = new Thread(rodarScript);
threadScript.Start();
}
}
}
XAML:
<Window x:Class="AsyncIronPython.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:AsyncIronPython"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="gridScript">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<TextBox x:Name="textBoxScript" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="3" AcceptsReturn="True" AcceptsTab="True" />
<Button x:Name="buttonScript" Click="buttonScript_Click" VerticalAlignment="Center" HorizontalAlignment="Stretch" Content="Execute" Grid.Row="1" Margin="3" />
</Grid>
</Window>
Hope this helps.
Thank you #BengEg and people, that was exactly what I was looking for. I was trying to be able to create animations in textBoxes, Grids, User Controls in general, using IronPython script inside C# WPF. So, I was having trouble to find a way of doing so, since the User Controls are being used by another threads in my program. So, here is the final "Testing Scripting code".
CSharp
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.IO;
using System.Threading;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace AsyncIronPython
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string script;
ScriptEngine engine;
ScriptScope scope;
Thread threadScript;
public MainWindow()
{
InitializeComponent();
engine = Python.CreateEngine();
scope = engine.CreateScope();
scope.SetVariable("objetoEditavel", gridScript);
scope.SetVariable("execute_in_ui", new Action<object>(ExecuteInUI));
}
public void ExecuteInUI(object obj)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
var op = engine.CreateOperations(scope);
op.Invoke(obj);
}));
}
public void rodarScript()
{
try
{
//PARTE PARA ADICIONAR BIBLIOTECAS BASICAS PARA DESENVOLVIMENTO COM OS SCRIPTS
script = #"#Reference the WPF assemblies
import clr
clr.AddReferenceByName(""PresentationFramework, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"")
clr.AddReferenceByName(""PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"")
import System.Windows
def getMyObject():
return objetoEditavel
objeto = getMyObject()
#Atalhos de referencias para adicionar
Thickness = System.Windows.Thickness
from System.Threading.Thread import Sleep
Debug = System.Diagnostics.Debug";
this.Dispatcher.Invoke((Action)(() =>{script = script + "\n" + textBoxScript.Text;}));
var source = engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
source.Execute(scope);
}
catch (Exception qualquerExcecaoEncontrada)
{
MessageBox.Show(qualquerExcecaoEncontrada.ToString(), "Scripting Test do Mier", MessageBoxButton.OK);
}
}
private void buttonScript_Click(object sender, RoutedEventArgs e)
{
threadScript = new Thread(rodarScript);
threadScript.Start();
}
}
}
XAML
<Window x:Class="AsyncIronPython.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:AsyncIronPython"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<TextBox x:Name="textBoxScript" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="261,3,3,3" AcceptsReturn="True" AcceptsTab="True" Background="#FFFFD6D6" />
<Button x:Name="buttonScript" Click="buttonScript_Click" VerticalAlignment="Center" HorizontalAlignment="Stretch" Content="Execute" Grid.Row="1" Margin="3" />
<Grid x:Name="gridScript" HorizontalAlignment="Left" Height="50" Margin="10,10,0,0" VerticalAlignment="Top" Width="50" Background="Black"/>
</Grid>
</Window>
IronPython Script inside gridScript (will basically create an animation of this black box grid to grow in a interval of 50 miliseconds.
def inc_width():
objeto.Width = objeto.Width + 1
for num in range(1,100):
execute_in_ui(inc_width)
Sleep(50)

Silverlight ComboBox value does not fall within the expected range

We are developing a silverlight 5 application. Within our application we use the combobox control.
When a combobox is open (IsDropDownOpen = true) and the combobox has a selected value and the combobox is removed and readded in the visual tree during a SizeChange event, the following exception is thrown: "value does not fall within the expected range".
I managed to reproduce this error in the example code. Is this a Silverlight 5 issue/bug or am I doing something wrong?
<UserControl x:Class="SilverlightApplication3.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">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
</Grid>
</UserControl>
code behind
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 System.Threading;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
private ComboBox combo;
private Button b;
public MainPage()
{
InitializeComponent();
combo = new ComboBox() { Width = 100, Height = 20 };
combo.Items.Add(new ComboBoxItem() { Content = "Jaar", IsSelected = true});
LayoutRoot.Children.Add(combo);
LayoutRoot.SizeChanged += new SizeChangedEventHandler(LayoutRoot_SizeChanged);
b = new Button() { Content = "Crash Me" };
b.Click += new RoutedEventHandler(b_Click);
Grid.SetRow(b, 1);
LayoutRoot.Children.Add(b);
}
void b_Click(object sender, RoutedEventArgs e)
{
combo.IsDropDownOpen = true;
Width = 500;
}
void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
{
LayoutRoot.Children.Clear();
LayoutRoot.Children.Add(b);
LayoutRoot.Children.Add(combo);
}
}
}

After resolution change hidden animated window is transparent

I am animating a window's opacity
...
DoubleAnimation myDoubleAnimation =
new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromSeconds(0.25)), FillBehavior.Stop);
Storyboard.SetTargetName(myDoubleAnimation, "wndNumpad");
Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Window.OpacityProperty));
m_fadeOut = new Storyboard();
m_fadeOut.Children.Add(myDoubleAnimation);
m_fadeOut.Completed += new EventHandler(FadeOut_Completed);
...
private void FadeOut_Completed(object sender, EventArgs e)
{
// Only hide the running instance
this.Visibility = System.Windows.Visibility.Hidden;
// this.Close();
}
If the screen resolution of a monitor is changed after FadeOut_Completed() has run i.e. the window's opacity was animated and the window is hidden. Then reshowing the window will display the window almost transparent. At a guess I would say with the opacity it had when the window was hidden although the Window.Opacity property claims an opacity of 1. If I don't animate but simply set the opacity to 0 and hide the window and after the resolution change set the opacity back to 1 the window is reshown as expected. I have also tried setting the opacity back to 1 in the FadeOut_Completed.
Does anyone have an idea what is happening and how I can avoid the issue?
Regards
Markus
You must to have a transparent window (AllowsTransparency="True"), no-resizable (ResizeMode="NoResize") and with no border (WindowStyle="None"). In C# code, I created a DoubleAnimation that change the opacity of the window, and when it is complete, the window will be closed.
XAML code:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Background="Red" WindowStyle="None" AllowsTransparency="True" ResizeMode="NoResize">
<Grid>
</Grid>
</Window>
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Windows.Media.Animation;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DoubleAnimation da = new DoubleAnimation();
da.From = 1;
da.To = 0;
da.Duration = new Duration(TimeSpan.FromSeconds(2));
da.Completed += new EventHandler(da_Completed);
this.BeginAnimation(OpacityProperty, da);
}
void da_Completed(object sender, EventArgs e)
{
this.Close();
}
}
}

Categories

Resources