How can i get the startX and startY position of the rectToGetXAndY. This piece of functionality is very critical to my application but it is driving me crazy. The only approach that comes to my mind is to ask the user to manually click on the top left border of the grid and then handle mouseleftbuttondown event. Obviously this is not the solution i want. Here is my code :-
<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="DelSilverlightApp.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="600" d:DesignWidth="800">
<Grid x:Name="LayoutRoot" Background="DarkSlateGray">
<Grid x:Name="rectToGetXAndY" Background="HotPink" Width="300" Height="300" HorizontalAlignment="Center" VerticalAlignment="Center">
</Grid>
</Grid>
</UserControl>
EDIT :-
This the 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;
namespace DelSilverlightApp
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
GeneralTransform gt = rectToGetXAndY.TransformToVisual(null);
Point p = gt.Transform(new Point(0, 0));
MessageBox.Show(p.X + " " + p.Y);
}
}
}
Thanks in advance :)
I made it work using #AnthonyWJones' code using the following:
XAML
<UserControl x:Class="GetPositionUi.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"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="DarkSlateGray">
<Grid x:Name="rectToGetXAndY"
Background="HotPink"
Width="300"
Height="300"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBlock x:Name="PositionTextBlock" Text="{Binding Path=ReferencePosition}"/>
</Grid>
</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;
namespace GetPositionUi
{
public partial class MainPage : UserControl
{
#region ReferencePosition
/// <summary>
/// ReferencePosition Dependency Property
/// </summary>
public static readonly DependencyProperty ReferencePositionProperty =
DependencyProperty.Register("ReferencePosition", typeof(Point), typeof(MainPage),
new PropertyMetadata((Point)(new Point(0, 0)),
new PropertyChangedCallback(OnReferencePositionChanged)));
/// <summary>
/// Gets or sets the ReferencePosition property. This dependency property
/// indicates the reference position of the child element.
/// </summary>
public Point ReferencePosition
{
get { return (Point)GetValue(ReferencePositionProperty); }
set { SetValue(ReferencePositionProperty, value); }
}
/// <summary>
/// Handles changes to the ReferencePosition property.
/// </summary>
private static void OnReferencePositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((MainPage)d).OnReferencePositionChanged(e);
}
/// <summary>
/// Provides derived classes an opportunity to handle changes to the ReferencePosition property.
/// </summary>
protected virtual void OnReferencePositionChanged(DependencyPropertyChangedEventArgs e)
{
}
#endregion
public MainPage()
{
InitializeComponent();
}
protected override Size ArrangeOverride(Size finalSize)
{
var arrangedSize = base.ArrangeOverride(finalSize);
GeneralTransform gt = rectToGetXAndY.TransformToVisual(LayoutRoot);
Point p = gt.Transform(new Point(0, 0));
ReferencePosition = p;
return arrangedSize;
}
}
}
The key here is letting the base arrange the controls first, then use the transform to find the position and finally returning the new arrangedSize.
I would not recommend showing a message box at this point, but you can use the dependency property changed callback to do anything you want with the updated position.
In Silveright you can use this code to determine the current X and Y position of rectToGetXAndY relative to LayoutRoot:-
GeneralTransform gt = rectToGetXAndY.TransformToVisual(LayoutRoot);
Point p = gt.Transform(new Point(0, 0));
You can use the VisualTreeHelper...
Vector vector = VisualTreeHelper.GetOffset(rectToGetXAndY);
Point currentPoint = new Point(vector.X, vector.Y);
Related
I have created a simple .net core wpf application to represent my problem. On the MainWindow there is a TextBox, which should be updated periodically via Binding. But the TextBox only shows 'Hello world' but not the time.
Thanks for any hints!
MainWindow.xaml:
<Window x:Class="WpfTest.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:WpfTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox Text="{Binding Path=DebugText}" TextWrapping="Wrap" Margin="10,191,10,192"/>
</Grid>
</Window>
MainWindow.xaml.cs:
using System.Windows;
namespace WpfTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly ViewModel _viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = _viewModel;
}
}
}
ViewModel.cs:
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace WpfTest
{
public class ViewModel : UserControl
{
private Timer _updateTimer;
public ViewModel()
{
DebugText = "Hello world";
AutoResetEvent timerEvent = new AutoResetEvent(true);
_updateTimer = new Timer(OnTimer, timerEvent, 1000, 1000);
}
private void OnTimer(object stateInfo)
{
Application.Current.Dispatcher.Invoke(() =>
{
DebugText = DateTime.Now.ToString();
});
}
public string DebugText
{
get => (string)GetValue(DebugTextProperty);
set => SetValue(DebugTextProperty, value);
}
public static readonly DependencyProperty DebugTextProperty =
DependencyProperty.Register("DebugText",
typeof(string),
typeof(MainWindow),
new PropertyMetadata(null));
}
}
I have created very small WPF application and facing one problem. I have below classes.
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticResourceVsDynamicResource
{
public class Employee
{
public string strName;
public int nId;
public Employee()
{
strName = "Default name";
nId = -1;
}
public string Name
{
get{return strName;}set{strName = value;}
}
public int ID
{
get{return nId;}set{nId = value;}
}
}
}
MainWindow.xamal.cs
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;
namespace StaticResourceVsDynamicResource
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.Resources["objEmployee"] = new Employee { Name = "Changed employee", ID = 100};
this.Resources.Add("myBrush",new SolidColorBrush(SystemColors.GrayTextColor));
}
}
}
MainWindow.xamal
<Window x:Class="StaticResourceVsDynamicResource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StaticResourceVsDynamicResource"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<x:ArrayExtension Type="{x:Type sys:String}" x:Key="objNames">
<sys:String>A1</sys:String>
<sys:String>A2</sys:String>
</x:ArrayExtension>
<local:Employee x:Key="objEmployee"></local:Employee>
</Window.Resources>
<Grid>
<Grid Height="100" HorizontalAlignment="Left" Margin="281,12,0,0" Name="grid3" VerticalAlignment="Top" Width="200" >
<ComboBox ItemsSource="{StaticResource ResourceKey=objNames}" Height="23" HorizontalAlignment="Left" Margin="48,37,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
</Grid>
</Grid>
Above xaml code is intresting. When I build this code I didn't get any error. For whatever reason I just shuffle position of <x:ArrayExtension> and <local:Employee> and I start getting below error.
The name 'InitializeComponent' does not exist in the current context
When I am declaring <local:Employee> before <x:ArrayExtenion> then only I am getting this error. I am sure this has to do something with namespace, but I am not able to figure it out. See the below code which is causing compilation error.
<Window.Resources>
<local:Employee x:Key="objEmployee"></local:Employee>
<x:ArrayExtension Type="{x:Type sys:String}" x:Key="objNames">
<sys:String>A1</sys:String>
<sys:String>A2</sys:String>
</x:ArrayExtension>
</Window.Resources>
Can anyone help? Seems to be a strange problem but it is...
Regards,
Hemant
I've had the same problem. The way I resolved it was by changing the build action of the XAML file to Page.
To credit the source where I found the solution:
http://blog.mahop.net/post/Compile-Error-for-WPF-Files-The-name-InitializeComponent-does-not-exist-in-the-current-context.aspx
I'm trying to do a simple application that, when a user touchs a screen, app creates simple point, ellipse, or sth 2d object, and when user moves his finger it should follow, but also when there is a scond touch at the same time new object also has to be created and do the same thing with respect to users movement. Whenever user fingersup, object will be deleted.
To do this, I'm trying to change the touchdrawing code from this link http://www.cookingwithxaml.com/recipes/wpf4/wpf4touch.zip but I couldn't figure out which method should I need to change ?
Can you give advice about that please ?
Thanks.
Here is some sample xaml/C# code that does what I think you want:
MainWindow.xaml:
<Window x:Class="MultitouchExperiments.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">
<Grid>
<Canvas
x:Name="TouchCanvas"
TouchDown="TouchCanvas_TouchDown" TouchUp="TouchCanvas_TouchUp"
TouchMove="TouchCanvas_TouchMove" TouchLeave="TouchCanvas_TouchLeave"
TouchEnter="TouchCanvas_TouchEnter"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Background="Black"
IsManipulationEnabled="True" />
</Grid>
</Window>
MainWindow.xaml.cs:
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.Diagnostics;
namespace MultitouchExperiments
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Dictionary<TouchDevice, Ellipse> _Followers = new Dictionary<TouchDevice, Ellipse>();
public MainWindow()
{
InitializeComponent();
}
private void TouchCanvas_TouchDown(object sender, TouchEventArgs e)
{
TouchCanvas.CaptureTouch(e.TouchDevice);
Ellipse follower = new Ellipse();
follower.Width = follower.Height = 50;
follower.Fill = Brushes.White;
follower.Stroke = Brushes.White;
TouchPoint point = e.GetTouchPoint(TouchCanvas);
follower.RenderTransform = new TranslateTransform(point.Position.X, point.Position.Y);
_Followers[e.TouchDevice] = follower;
TouchCanvas.Children.Add(follower);
}
private void TouchCanvas_TouchUp(object sender, TouchEventArgs e)
{
TouchCanvas.ReleaseTouchCapture(e.TouchDevice);
TouchCanvas.Children.Remove(_Followers[e.TouchDevice]);
_Followers.Remove(e.TouchDevice);
}
private void TouchCanvas_TouchMove(object sender, TouchEventArgs e)
{
if (e.TouchDevice.Captured == TouchCanvas)
{
Ellipse follower = _Followers[e.TouchDevice];
TranslateTransform transform = follower.RenderTransform as TranslateTransform;
TouchPoint point = e.GetTouchPoint(TouchCanvas);
transform.X = point.Position.X;
transform.Y = point.Position.Y;
}
}
private void TouchCanvas_TouchLeave(object sender, TouchEventArgs e)
{
//Debug.WriteLine("leave " + e.TouchDevice.Id);
}
private void TouchCanvas_TouchEnter(object sender, TouchEventArgs e)
{
//Debug.WriteLine("enter " + e.TouchDevice.Id);
}
}
}
Can I set the Content property of a ContentControl to a DrawingVisual object? It says in the documentation that the content can be anything but I tried and nothing shows up when I add the control to canvas. Is it possible and if it is can you post the full code that adds a ContentControl, whose content is a DrawingVisual, to a canvas?
Can I set the Content property of a ContentControl to a DrawingVisual object?
Technically, yes, you can. However, that is probably not what you want. A DrawingVisual added to a ContentControl will simply display the string "System.Windows.Media.DrawingVisual". The following code within a grid will demonstrate this easilly:
<Button>
<DrawingVisual/>
</Button>
To use a DrawingVisual properly, you need to encapsulate it within a FrameworkElement. See the Microsoft Reference.
Thus, the following code should help do what you want.
<Window x:Class="TestDump.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestDump"
Title="Window1" Height="300" Width="600" >
<Grid>
<Canvas>
<Button >
<local:MyVisualHost Width="600" Height="300"/>
</Button>
</Canvas>
</Grid>
</Window>
And on the C# side:
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;
namespace TestDump
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
public class MyVisualHost : FrameworkElement
{
private VisualCollection _children;
public MyVisualHost()
{
_children = new VisualCollection(this);
_children.Add(CreateDrawingVisualRectangle());
}
// Create a DrawingVisual that contains a rectangle.
private DrawingVisual CreateDrawingVisualRectangle()
{
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Create a rectangle and draw it in the DrawingContext.
Rect rect = new Rect(new System.Windows.Point(160, 100), new System.Windows.Size(320, 80));
drawingContext.DrawRectangle(System.Windows.Media.Brushes.Blue, (System.Windows.Media.Pen)null, rect);
// Persist the drawing content.
drawingContext.Close();
return drawingVisual;
}
// Provide a required override for the VisualChildrenCount property.
protected override int VisualChildrenCount
{
get { return _children.Count; }
}
// Provide a required override for the GetVisualChild method.
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= _children.Count)
{
throw new ArgumentOutOfRangeException();
}
return _children[index];
}
}
}
I have a problem updating the WPF Designer when binding to custom dependency properties.
In the following example, I create a simple Ellipse that I would like to fill with my custom MyAwesomeFill property. The MyAwesomeFill has a default value of a Yellow SolidColor brush.
The problem is that in the control form of the designer I cannot see the default fill of the ellipse (Yellow), instead the ellipse is filled with SolidColor (#00000000). However, when I run the application everything works PERFECTLY.
Do you have any ideas why this may be happenning?
Thanks.
Here's the code that I use:
XAML:
<UserControl x:Class="TestApplication.MyEllipse"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<Ellipse Stroke="Black" StrokeThickness="5" Fill="{Binding MyAwesomeFill}"></Ellipse>
</Grid>
</UserControl>
C#:
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;
namespace TestApplication
{
public partial class MyEllipse : UserControl
{
#region Dependency property MyAwesomeFill
//Define and register dependency property
public static readonly DependencyProperty MyAwesomeFillProperty = DependencyProperty.Register(
"MyAwesomeFill",
typeof(Brush),
typeof(MyEllipse),
new PropertyMetadata(new SolidColorBrush(Colors.Yellow), new PropertyChangedCallback(OnMyAwesomeFillChanged))
);
//property wrapper
public Brush MyAwesomeFill
{
get { return (Brush)GetValue(MyAwesomeFillProperty); }
set { SetValue(MyAwesomeFillProperty, value); }
}
//callback
private static void OnMyAwesomeFillChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
MyEllipse m = (MyEllipse)obj;
m.OnMyAwesomeFillChanged(e);
}
#endregion
//callback
protected virtual void OnMyAwesomeFillChanged(DependencyPropertyChangedEventArgs e)
{
}
public MyEllipse()
{
InitializeComponent();
DataContext = this;
}
}
}
Code behind is not guaranteed to be run by the designer. If you add your MyEllipse control to a window it will run (ellipse in window has yellow background) but not when you look at the control directly. This means it will work for users of your control which is what is important.
To fix it to look good when opening up MyEllipse in the designer, add a fallback value.
<Ellipse
Stroke="Black"
StrokeThickness="5"
Fill="{Binding MyAwesomeFill, FallbackValue=Yellow}">
</Ellipse>