Search Results

Search found 112 results on 5 pages for 'uielement'.

Page 5/5 | < Previous Page | 1 2 3 4 5 

  • Mousin' down the PathListBox

    - by T
    While modifying the standard media player with a new look and feel for Ineta Live I saw a unique opportunity to use their logo with a dotted I with and attached arc as the scrub control. So I created a PathListBox that I wanted an object to follow when a user did a click and drag action.  Below is how I solved the problem.  Please let me know if you have improvements or know of a completely different way.  I am always eager to learn. First, I created a path using the pen tool in Expression Blend (see the yellow line in image below).  Then I right clicked that path and chose [Path] --> [Make Layout Path].   That created a new PathListBox.  Then I chose the object I want to move down the new PathListBox and Placed it as a child in the Objects and Timeline window (see image below).  If the child object (the thing the user will click and drag) is XAML, it will move much smoother than images. Just as another side note, I wanted there to be no highlight when the user selects the “ball” to drag and drop.  This is done by editing the ItemContainerStyle under Additional Templates on the PathListBox.  Post a question if you need help on this and I will expand my explanation. Here is a pic of the object and the path I wanted it to follow.  I gave the path a yellow solid brush here so you could see it but when I lay this over another object, I will make the path transparent.   To animate this object down the path, the trick is to animate the Start number for the LayoutPath.  Not the StartItemIndex, the Start above Span. In order to enable animation when a user clicks and drags, I put in the following code snippets in the code behind. the DependencyProperties are not necessary for the Drag control. namespace InetaPlayer{ public partial class PositionControl : UserControl { private bool _mouseDown; private double _maxPlayTime; public PositionControl() { // Required to initialize variables InitializeComponent(); //mouse events for scrub control positionThumb.MouseLeftButtonDown += new MouseButtonEventHandler(ValueThumb_MouseLeftButtonDown); positionThumb.MouseLeftButtonUp += new MouseButtonEventHandler(ValueThumb_MouseLeftButtonUp); positionThumb.MouseMove += new MouseEventHandler(ValueThumb_MouseMove); positionThumb.LostMouseCapture += new MouseEventHandler(ValueThumb_LostMouseCapture); } // exposed for binding to real slider using a DependencyProperty enables animation, styling, binding, etc.... public double MaxPlayTime { get { return (double)GetValue(MaxPlayTimeProperty); } set { SetValue(MaxPlayTimeProperty, value); } } public static readonly DependencyProperty MaxPlayTimeProperty = DependencyProperty.Register("MaxPlayTime", typeof(double), typeof(PositionControl), null);   // exposed for binding to real slider using a DependencyProperty enables animation, styling, binding, etc....   public double CurrSliderValue { get { return (double)GetValue(CurrSliderValueProperty); } set { SetValue(CurrSliderValueProperty, value); } }   public static readonly DependencyProperty CurrSliderValueProperty = DependencyProperty.Register("CurrSliderValue", typeof(double), typeof(PositionControl), new PropertyMetadata(0.0, OnCurrSliderValuePropertyChanged));   private static void OnCurrSliderValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { PositionControl control = d as PositionControl; control.OnCurrSliderValueChanged((double)e.OldValue, (double)e.NewValue); }   private void OnCurrSliderValueChanged(double oldValue, double newValue) { _maxPlayTime = (double) GetValue(MaxPlayTimeProperty); if (!_mouseDown) if (_maxPlayTime!=0) sliderPathListBox.LayoutPaths[0].Start = newValue / _maxPlayTime; else sliderPathListBox.LayoutPaths[0].Start = 0; }  //mouse control   void ValueThumb_MouseMove(object sender, MouseEventArgs e) { if (!_mouseDown) return; //get the offset of how far the drag has been //direction is handled automatically (offset will be negative for left move and positive for right move) Point mouseOff = e.GetPosition(positionThumb); //Divide the offset by 1000 for a smooth transition sliderPathListBox.LayoutPaths[0].Start +=mouseOff.X/1000; _maxPlayTime = (double)GetValue(MaxPlayTimeProperty); SetValue(CurrSliderValueProperty ,sliderPathListBox.LayoutPaths[0].Start*_maxPlayTime); }   void ValueThumb_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { _mouseDown = false; } void ValueThumb_LostMouseCapture(object sender, MouseEventArgs e) { _mouseDown = false; } void ValueThumb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { _mouseDown = true; ((UIElement)positionThumb).CaptureMouse(); }   }}  I made this into a user control and exposed a couple of DependencyProperties in order to bind it to a standard Slider in the overall project.  This control is embedded into the standard Expression media player template and is used to replace the standard scrub bar.  When the player goes live, I will put a link here.

    Read the article

  • WPF MVVM Trigger Animation on MainWindow close

    - by Scott
    I'm using trying to implement MVVM in my app. I have a MainWindow.xaml and a MainWindowViewModel. I'm in the process of removing all of the code-behind code from the MainWindow.xaml but I'm stuck on one final piece. In my pre-MVVM setup I started an animation in the MainWindow.xaml.cs that would fade out the form before closing it. Since Closing is not a RoutedEvent, I had to use code-behind to get this to work. My VM has the following two properties that can be bound: ClosingWindow and CloseWindow. My goal was to bind a DataTrigger in my MainWindowStyle to the ClosingWindow property of the VM. When ClosingWindow was set to True, it would start an animation using the following XAML: <DataTrigger Binding="{Binding ClosingWindow}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2"/> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> </DataTrigger> Somehow (insert magic here) I was going to set CloseWindow on the VM, via Binding, to True when the animation completed, which would then use an AttachedBehavior to Close the Window. The AttachedBehavior works perfectly when I just set CloseWindow directly using the following XAML: <DataTrigger Binding="{Binding CloseWindow}" Value="True"> <Setter Property="ab:WindowCloseBehavior.Close" Value="True"/> </DataTrigger> ...but I want to reproduce the form fade before the form actually closes. So there are two issues that I've run into: First, the animation doesn't work. I enter the trigger correctly (I've taken out the animation and put a Setter statement in there that changes the Title of the MainWindow to "Closing" and it changes correctly when ClosingWindow = True) but the DoubleAnimation never does anything. Second, there's no way to set the value of CloseWindow once the animation is complete. I looked at Marlon Grech's animation code but that won't work on DataTriggers. I can't publish a RoutedEvent because my VM doesn't descend from UIElement, and I've been Googling all day trying to come up with a clever, MVVM-friendly way to do this with no luck. So any ideas why that animation doesn't do anything? And more importantly, how would you solve the entire problem of animating a form fade on close from the VM? I don't doubt that my entire solution to this problem might be whacked so I'm open to just about anything.

    Read the article

  • WPF FlowDocument: force calculation of height etc. "off screen"

    - by Lars
    My target: a DocumentPaginator which takes a FlowDocument with a table, which splits the table to fit the pagesize and repeat the header/footer (special tagged TableRowGroups) on every page. For splitting the table I have to know the heights of its rows. While building the FlowDocument-table by code, the height/width of the TableRows are 0 (of course). If I assign this document to a FlowDocumentScrollViewer (PageSize is set), the heights etc. are calculated. Is this possible without using an UI-bound object? Instantiating a FlowDocumentScrollViewer which is not bound to a window doesn't force the pagination/calculation of the heights. This is how I determine the height of a TableRow (which works perfectly for documents shown by a FlowDocumentScrollViewer): FlowDocument doc = BuildNewDocument(); // what is the scrollviewer doing with the FlowDocument? FlowDocumentScrollViewer dv = new FlowDocumentScrollViewer(); dv.Document = doc; dv.Arrange(new Rect(0, 0, 0, 0)); TableRowGroup dataRows = null; foreach (Block b in doc.Blocks) { if (b is Table) { Table t = b as Table; foreach (TableRowGroup g in t.RowGroups) { if ((g.Tag is String) && ((String)g.Tag == "dataRows")) { dataRows = g; break; } } } if (dataRows != null) break; } if (dataRows != null) { foreach (TableRow r in dataRows.Rows) { double maxCellHeight = 0.0; foreach (TableCell c in r.Cells) { Rect start = c.ElementStart.GetCharacterRect(LogicalDirection.Forward); Rect end = c.ElementEnd.GetNextInsertionPosition(LogicalDirection.Backward).GetCharacterRect(LogicalDirection.Forward); double cellHeight = end.Bottom - start.Top; if (cellHeight > maxCellHeight) maxCellHeight = cellHeight; } System.Diagnostics.Trace.WriteLine("row " + dataRows.Rows.IndexOf(r) + " = " + maxCellHeight); } } Edit: I added the FlowDocumentScrollViewer to my example. The call of "Arrange" forces the FlowDocument to calculate its heights etc. I would like to know, what the FlowDocumentScrollViewer is doing with the FlowDocument, so I can do it without the UIElement. Is it possible?

    Read the article

  • How to access a named element in a control that inherits from a templated control

    - by Mrt
    Hello this is similar to http://stackoverflow.com/questions/2620165/how-to-access-a-named-element-of-a-derived-user-control-in-silverlight with the difference is inheriting from a templated control, not a user control. I have a templated control called MyBaseControl <Style TargetType="Problemo:MyBaseControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Problemo:MyBaseControl"> <Grid x:Name="LayoutRoot" Background="White"> <Border Name="HeaderControl" Background="Red" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> public class MyBaseControl : Control { public UIElement Header { get; set; } public MyBaseControl() { DefaultStyleKey = typeof(MyBaseControl); } public override void OnApplyTemplate() { base.OnApplyTemplate(); var headerControl = GetTemplateChild("HeaderControl") as ContentPresenter; if (headerControl != null) headerControl.Content = Header; } } I have another control called myControl which inherits from MyBaseControl Control <me:MyBaseControl x:Class="Problemo.MyControl" 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:me="clr-namespace:Problemo" d:DesignHeight="300" d:DesignWidth="400"> <me:MyBaseControl.Header> <TextBlock Name="xxx" /> </me:MyBaseControl.Header> </me:MyBaseControl> public partial class MyControl : MyBaseControl { public string Text { get; set; } public MyControl(string text) { InitializeComponent(); Text = text; Loaded += MyControl_Loaded; } void MyControl_Loaded(object sender, RoutedEventArgs e) { base.ApplyTemplate(); xxx.Text = Text; } } The issue is xxx is null. How do I access the xxx control in the code behind ?

    Read the article

  • C# - How to override GetHashCode with Lists in object

    - by Christian
    Hi, I am trying to create a "KeySet" to modify UIElement behaviour. The idea is to create a special function if, eg. the user clicks on an element while holding a. Or ctrl+a. My approach so far, first lets create a container for all possible modifiers. If I would simply allow a single key, it would be no problem. I could use a simple Dictionary, with Dictionary<Keys, Action> _specialActionList If the dictionary is empty, use the default action. If there are entries, check what action to use depending on current pressed keys And if I wasn't greedy, that would be it... Now of course, I want more. I want to allow multiple keys or modifiers. So I created a wrapper class, wich can be used as Key to my dictionary. There is an obvious problem when using a more complex class. Currently two different instances would create two different key, and thereby he would never find my function (see code to understand, really obvious) Now I checked this post: http://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array which helped a little. But my question is, is my basic design for the class ok. Should I use a hashset to store the modifier and normal keyboardkeys (instead of Lists). And If so, how would the GetHashCode function look like? I know, its a lot of code to write (boring hash functions), some tips would be sufficient to get me started. Will post tryouts here... And here comes the code so far, the Test obviously fails... public class KeyModifierSet { private readonly List<Key> _keys = new List<Key>(); private readonly List<ModifierKeys> _modifierKeys = new List<ModifierKeys>(); private static readonly Dictionary<KeyModifierSet, Action> _testDict = new Dictionary<KeyModifierSet, Action>(); public static void Test() { _testDict.Add(new KeyModifierSet(Key.A), () => Debug.WriteLine("nothing")); if (!_testDict.ContainsKey(new KeyModifierSet(Key.A))) throw new Exception("Not done yet, help :-)"); } public KeyModifierSet(IEnumerable<Key> keys, IEnumerable<ModifierKeys> modifierKeys) { foreach (var key in keys) _keys.Add(key); foreach (var key in modifierKeys) _modifierKeys.Add(key); } public KeyModifierSet(Key key, ModifierKeys modifierKey) { _keys.Add(key); _modifierKeys.Add(modifierKey); } public KeyModifierSet(Key key) { _keys.Add(key); } }

    Read the article

  • Erratic behavior with XPS editing: what could be going wrong?

    - by Ariel Arjona
    Hello folks, I'm working on a class that annotates existing XPS documents. The problem I've been having is that some annotations randomly don't make it to the finished document. The following test code is supposed to draw a rectangle on every page. On random pages the rectangle does not appear. Upon inspection of the page XML, the tags for the rectangle are missing. I run the program again and sometimes it appears on that particular page, sometimes it's then missing from some other page, sometimes from all but 1, and so on. public void TestXpsAnnotate() { var xpsFile = this.GetXpsFile(); var xpsDoc = new XpsDocument(xpsFile, FileAccess.Read); FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence(); // new XPS document var newFds = new FixedDocumentSequence(); var newDocRef = new DocumentReference(); var newFixedDoc = new FixedDocument(); // get documents foreach (var docRef in docSeq.References) { FixedDocument fixedDoc = docRef.GetDocument(true); // get pages foreach (PageContent pageContent in fixedDoc.Pages) { var newPageContent = new PageContent(); newPageContent.Source = pageContent.Source; (newPageContent as IUriContext).BaseUri = ((IUriContext)pageContent).BaseUri; FixedPage fixedPage = newPageContent.GetPageRoot(true); var r = new System.Windows.Shapes.Rectangle() { Width = 300, Height = 400, Stroke = new SolidColorBrush(Colors.Red), Fill = new SolidColorBrush(Colors.Yellow), StrokeThickness = 3, }; //var r = new TextBlock(); //r.Text = "BLAH"; //r.Foreground = new SolidColorBrush(Colors.Red); var theCanvas = fixedPage.Children.Cast<UIElement>().OfType<Canvas>().First(); theCanvas.Children.Add(r); Canvas.SetLeft(r, 10); Canvas.SetTop(r, 10); fixedPage.UpdateLayout(); newFixedDoc.Pages.Add(newPageContent); } } xpsDoc.Close(); newDocRef.SetDocument(newFixedDoc); newFds.References.Add(newDocRef); string outputFile = this.GetOutputFile(); if (File.Exists(outputFile)) { File.Delete(outputFile); } var newXpsDoc = new XpsDocument(outputFile, FileAccess.ReadWrite); var writer = XpsDocument.CreateXpsDocumentWriter(newXpsDoc); writer.Write(newFds); newXpsDoc.Close(); } This code follows the examples I've seen around the internet and it seems to do what it's supposed to, when it works. Any idea what could be going wrong here?

    Read the article

  • Why won't this hit test fire a second time? wpf

    - by csciguy
    All, I have a main window that contains two custom objects (AnimatedCharacter). These objects are nothing but images. These images might contain transparent portions. One of these objects slightly overlaps the other object. There is a listener attached to the main window and is as follows. private void Window_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e) { Point pt = e.GetPosition((UIElement)sender); //store off the mouse pt hitPointMouse = pt; //clear the result list hitResultsSubList.Clear(); EllipseGeometry m_egHitArea = new EllipseGeometry(pt, 1, 1); VisualTreeHelper.HitTest(sender as Visual, HitTestFilterFuncNew, new HitTestResultCallback(HitTestCallback), new GeometryHitTestParameters(m_egHitArea)); //Check all sub items you have now hit if (hitResultsSubList.Count > 0) { CheckSubHitItems(hitResultsSubList); } } The idea is to filter out only a select group of items (called AnimatedCharacters). The hittest and filters are as follows public HitTestResultBehavior HitTestCallback(HitTestResult htrResult) { IntersectionDetail idDetail = ((GeometryHitTestResult)htrResult).IntersectionDetail; switch (idDetail) { case IntersectionDetail.FullyContains: return HitTestResultBehavior.Continue; case IntersectionDetail.Intersects: return HitTestResultBehavior.Continue; case IntersectionDetail.FullyInside: return HitTestResultBehavior.Continue; default: return HitTestResultBehavior.Stop; } } public HitTestFilterBehavior HitTestFilterFuncNew(DependencyObject potentialHitTestTarget) { if (potentialHitTestTarget.GetType() == typeof(AnimatedCharacter)) { hitResultsSubList.Add(potentialHitTestTarget as AnimatedCharacter); } return HitTestFilterBehavior.Continue; } This returns me back a list (called hitResultsSubList) that I attempt to then process further. I want to take everything in the hitResultsSubList and run a hit test on it again. This time, the hit test will be checking alpha levels on the particular animatedCharacter object. private void CheckSubHitItems(List<DependencyObject> hitResultsSub) { for(int i = 0; i<hitResultsSub.Count; i++) { hitResultsList.Clear(); AnimatedCharacter ac = hitResultsSub[i] as AnimatedCharacter; try { //DEBUGGER SKIPS THIS NEXT LINE EVERY SINGLE TIME. VisualTreeHelper.HitTest(ac, null, new HitTestResultCallback(hitCallBack), new PointHitTestParameters(hitPointMouse)); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); } if (hitResultsList.Count > 0) { //do something here } } } Here is my problem now. The hit test in the second function (CheckSubHitItems) never gets called. There are definitely items (DependencyObjects of the type AnimatedCharacter) in the hitResultSub, but no matter what, the second hit test will not fire. I can walk the for loop fine, but when that line is hit, I get the following console statement. Step into: Stepping over non-user code 'System.MulticastDelegate.CtorClosed' No exceptions are thrown. Any help is appreciated.

    Read the article

  • How to access a named element of a derived user control in silverlight ?

    - by Mrt
    Hello, I have a custom base user control in silverlight. <UserControl x:Class="Problemo.MyBaseControl" 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"> <Border Name="HeaderControl" Background="Red" /> </Grid> </UserControl> With the following code behind public partial class MyBaseControl : UserControl { public UIElement Header { get; set; } public MyBaseControl() { InitializeComponent(); Loaded += MyBaseControl_Loaded; } void MyBaseControl_Loaded(object sender, RoutedEventArgs e) { HeaderControl.Child = Header; } } I have a derived control. <me:MyBaseControl x:Class="Problemo.MyControl" 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:me="clr-namespace:Problemo" d:DesignHeight="300" d:DesignWidth="400"> <me:MyBaseControl.Header> <TextBlock Name="header" Text="{Binding Text}" /> </me:MyBaseControl.Header> </me:MyBaseControl> With the following code behind. public partial class MyControl : MyBaseControl { public string Text { get; set; } public MyControl(string text) { InitializeComponent(); Text = text; } } I'm trying to set the text value of the header textblock in the derived control. It would be nice to be able to set both ways, i.e. with databinding or in the derived control code behind, but neither work. With the data binding, it doesn't work. If I try in the code behind I get a null reference to 'header'. This is silverlight 4 (not sure if that makes a difference) Any suggestions on how to do with with both databinding and in code ? Cheers

    Read the article

  • WPF: How to properly override the methods when creating custom control

    - by EV
    Hi, I am creating a custom control Toolbox that is derived from ItemsControl. This toolbox is supposed to be filled with icons coming from the database. The definition looks like this: public class Toolbox : ItemsControl { protected override DependencyObject GetContainerForItemOverride() { return new ToolboxItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return (item is ToolboxItem); } } Toolboxitem is derived from ContentControl. public class ToolboxItem : ContentControl { static ToolboxItem() { FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem), new FrameworkPropertyMetadata(typeof(ToolboxItem))); } } Since the number of icons stored in a database is not known I want to use the data template: <DataTemplate x:Key="ToolBoxTemplate"> <StackPanel> <Image Source="{Binding Path=url}" /> </StackPanel> </DataTemplate> Then I want the Toolbox to use the template. <Toolbox x:Name="NewLibrary" ItemsSource="{Binding}" ItemTemplate="ToolBoxtemplate"> </Toolbox> I'm using ADO.NET entity framework to connect to a database. The code behind: SystemicsAnalystDBEntities db = new SystemicsAnalystDBEntities(); private void Window_Loaded(object sender, RoutedEventArgs e) { NewLibrary.ItemsSource = from c in db.Components select c; } However, there is a problem. When the code is executed, it displays the object from the database (as the ItemSource property is set to the object from the database) and not the images. It does not use the template. When I use the static images source it works in the right way I found out that I need to override the PrepareContainerForItemOverride method.But I don't know how to add the template to it. Thanks a lot for any comments. Additional Information Here is the ControlTemplate for ToolboxItem: <ControlTemplate TargetType="{x:Type s:ToolboxItem}"> <Grid> <Rectangle Name="Border" StrokeThickness="1" StrokeDashArray="2" Fill="Transparent" SnapsToDevicePixels="true" /> <ContentPresenter Content="{TemplateBinding ContentControl.Content}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Stroke" Value="Gray" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate>

    Read the article

  • Algorithm for dragging objects on a fixed grid

    - by FlyingStreudel
    Hello, I am working on a program for the mapping and playing of the popular tabletop game D&D :D Right now I am working on getting the basic functionality like dragging UI elements around, snapping to the grid and checking for collisions. Right now every object when released from the mouse immediately snaps to the nearest grid point. This causes an issue when something like a player object snaps to a grid point that has a wall -or other- adjacent. So essentially when the player is dropped they wind up with some of the wall covering them. This is fine and working as intended, however the problem is that now my collision detection is tripped whenever you try to move this player because its sitting underneath a wall and because of this you cant drag the player anymore. Here is the relevant code: void UIObj_MouseMove(object sender, MouseEventArgs e) { blocked = false; if (dragging) { foreach (UIElement o in ((Floor)Parent).Children) { if (o.GetType() != GetType() && o.GetType().BaseType == typeof(UIObj) && Math.Sqrt(Math.Pow(((UIObj)o).cX - cX, 2) + Math.Pow(((UIObj)o).cY - cY, 2)) < Math.Max(r.Height + ((UIObj)o).r.Height, r.Width + ((UIObj)o).r.Width)) { double Y = e.GetPosition((Floor)Parent).Y; double X = e.GetPosition((Floor)Parent).X; Geometry newRect = new RectangleGeometry(new Rect(Margin.Left + (X - prevX), Margin.Top + (Y - prevY), Margin.Right + (X - prevX), Margin.Bottom + (Y - prevY))); GeometryHitTestParameters ghtp = new GeometryHitTestParameters(newRect); VisualTreeHelper.HitTest(o, null, new HitTestResultCallback(MyHitTestResultCallback), ghtp); } } if (!blocked) { Margin = new Thickness(Margin.Left + (e.GetPosition((Floor)Parent).X - prevX), Margin.Top + (e.GetPosition((Floor)Parent).Y - prevY), Margin.Right + (e.GetPosition((Floor)Parent).X - prevX), Margin.Bottom + (e.GetPosition((Floor)Parent).Y - prevY)); InvalidateVisual(); } prevX = e.GetPosition((Floor)Parent).X; prevY = e.GetPosition((Floor)Parent).Y; cX = Margin.Left + r.Width / 2; cY = Margin.Top + r.Height / 2; } } internal virtual void SnapToGrid() { double xPos = Margin.Left; double yPos = Margin.Top; double xMarg = xPos % ((Floor)Parent).cellDim; double yMarg = yPos % ((Floor)Parent).cellDim; if (xMarg < ((Floor)Parent).cellDim / 2) { if (yMarg < ((Floor)Parent).cellDim / 2) { Margin = new Thickness(xPos - xMarg, yPos - yMarg, xPos - xMarg + r.Width, yPos - yMarg + r.Height); } else { Margin = new Thickness(xPos - xMarg, yPos - yMarg + ((Floor)Parent).cellDim, xPos - xMarg + r.Width, yPos - yMarg + ((Floor)Parent).cellDim + r.Height); } } else { if (yMarg < ((Floor)Parent).cellDim / 2) { Margin = new Thickness(xPos - xMarg + ((Floor)Parent).cellDim, yPos - yMarg, xPos - xMarg + ((Floor)Parent).cellDim + r.Width, yPos - yMarg + r.Height); } else { Margin = new Thickness(xPos - xMarg + ((Floor)Parent).cellDim, yPos - yMarg + ((Floor)Parent).cellDim, xPos - xMarg + ((Floor)Parent).cellDim + r.Width, yPos - yMarg + ((Floor)Parent).cellDim + r.Height); } } } Essentially I am looking for a simple way to modify the existing code to allow the movement of a UI element that has another one sitting on top of it. Thanks!

    Read the article

  • WPF Blurry Images - Bitmap Class

    - by Luke
    I am using the following sample at http://blogs.msdn.com/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx within VB.NET. The code is shown below. I am having a problem when my application loads the CPU is pegging 50-70%. I have determined that the problem is with the Bitmap class. The OnLayoutUpdated() method is calling the InvalidateVisual() continously. This is because some points are not returning as equal but rather, Point(0.0,-0.5) Can anyone see any bugs within this code or know a better implmentation for pixel snapping a Bitmap image so it is not blurry? p.s. The sample code was in C#, however I believe that it was converted correctly. Imports System Imports System.Collections.Generic Imports System.Windows Imports System.Windows.Media Imports System.Windows.Media.Imaging Class Bitmap Inherits FrameworkElement ' Use FrameworkElement instead of UIElement so Data Binding works as expected Private _sourceDownloaded As EventHandler Private _sourceFailed As EventHandler(Of ExceptionEventArgs) Private _pixelOffset As Windows.Point Public Sub New() _sourceDownloaded = New EventHandler(AddressOf OnSourceDownloaded) _sourceFailed = New EventHandler(Of ExceptionEventArgs)(AddressOf OnSourceFailed) AddHandler LayoutUpdated, AddressOf OnLayoutUpdated End Sub Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(BitmapSource), GetType(Bitmap), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.AffectsMeasure, New PropertyChangedCallback(AddressOf Bitmap.OnSourceChanged))) Public Property Source() As BitmapSource Get Return DirectCast(GetValue(SourceProperty), BitmapSource) End Get Set(ByVal value As BitmapSource) SetValue(SourceProperty, value) End Set End Property Public Shared Function FindParentWindow(ByVal child As DependencyObject) As Window Dim parent As DependencyObject = VisualTreeHelper.GetParent(child) 'Check if this is the end of the tree If parent Is Nothing Then Return Nothing End If Dim parentWindow As Window = TryCast(parent, Window) If parentWindow IsNot Nothing Then Return parentWindow Else ' Use recursion until it reaches a Window Return FindParentWindow(parent) End If End Function Public Event BitmapFailed As EventHandler(Of ExceptionEventArgs) ' Return our measure size to be the size needed to display the bitmap pixels. ' ' Use MeasureOverride instead of MeasureCore so Data Binding works as expected. ' Protected Overloads Overrides Function MeasureCore(ByVal availableSize As Size) As Size Protected Overloads Overrides Function MeasureOverride(ByVal availableSize As Size) As Size Dim measureSize As New Size() Dim bitmapSource As BitmapSource = Source If bitmapSource IsNot Nothing Then Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If Me.VisualParent IsNot Nothing Then Dim window As Window = window.GetWindow(Me.VisualParent) If window IsNot Nothing Then ps = PresentationSource.FromVisual(window.GetWindow(Me.VisualParent)) ElseIf FindParentWindow(Me) IsNot Nothing Then ps = PresentationSource.FromVisual(FindParentWindow(Me)) End If End If ' If ps IsNot Nothing Then Dim fromDevice As Matrix = ps.CompositionTarget.TransformFromDevice Dim pixelSize As New Vector(bitmapSource.PixelWidth, bitmapSource.PixelHeight) Dim measureSizeV As Vector = fromDevice.Transform(pixelSize) measureSize = New Size(measureSizeV.X, measureSizeV.Y) Else measureSize = New Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight) End If End If Return measureSize End Function Protected Overloads Overrides Sub OnRender(ByVal dc As DrawingContext) Dim bitmapSource As BitmapSource = Me.Source If bitmapSource IsNot Nothing Then _pixelOffset = GetPixelOffset() ' Render the bitmap offset by the needed amount to align to pixels. dc.DrawImage(bitmapSource, New Rect(_pixelOffset, DesiredSize)) End If End Sub Private Shared Sub OnSourceChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) Dim bitmap As Bitmap = DirectCast(d, Bitmap) Dim oldValue As BitmapSource = DirectCast(e.OldValue, BitmapSource) Dim newValue As BitmapSource = DirectCast(e.NewValue, BitmapSource) If ((oldValue IsNot Nothing) AndAlso (bitmap._sourceDownloaded IsNot Nothing)) AndAlso (Not oldValue.IsFrozen AndAlso (TypeOf oldValue Is BitmapSource)) Then RemoveHandler DirectCast(oldValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded RemoveHandler DirectCast(oldValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed -= bitmap._sourceFailed; // 3.5 End If If ((newValue IsNot Nothing) AndAlso (TypeOf newValue Is BitmapSource)) AndAlso Not newValue.IsFrozen Then AddHandler DirectCast(newValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded AddHandler DirectCast(newValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed += bitmap._sourceFailed; // 3.5 End If End Sub Private Sub OnSourceDownloaded(ByVal sender As Object, ByVal e As EventArgs) InvalidateMeasure() InvalidateVisual() End Sub Private Sub OnSourceFailed(ByVal sender As Object, ByVal e As ExceptionEventArgs) Source = Nothing ' setting a local value seems scetchy... RaiseEvent BitmapFailed(Me, e) End Sub Private Sub OnLayoutUpdated(ByVal sender As Object, ByVal e As EventArgs) ' This event just means that layout happened somewhere. However, this is ' what we need since layout anywhere could affect our pixel positioning. Dim pixelOffset As Windows.Point = GetPixelOffset() If Not AreClose(pixelOffset, _pixelOffset) Then InvalidateVisual() End If End Sub ' Gets the matrix that will convert a Windows.Point from "above" the ' coordinate space of a visual into the the coordinate space ' "below" the visual. Private Function GetVisualTransform(ByVal v As Visual) As Matrix If v IsNot Nothing Then Dim m As Matrix = Matrix.Identity Dim transform As Transform = VisualTreeHelper.GetTransform(v) If transform IsNot Nothing Then Dim cm As Matrix = transform.Value m = Matrix.Multiply(m, cm) End If Dim offset As Vector = VisualTreeHelper.GetOffset(v) m.Translate(offset.X, offset.Y) Return m End If Return Matrix.Identity End Function Private Function TryApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean, ByVal throwOnError As Boolean, ByRef success As Boolean) As Windows.Point success = True If v IsNot Nothing Then Dim visualTransform As Matrix = GetVisualTransform(v) If inverse Then If Not throwOnError AndAlso Not visualTransform.HasInverse Then success = False Return New Windows.Point(0, 0) End If visualTransform.Invert() End If Point = visualTransform.Transform(Point) End If Return Point End Function Private Function ApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean) As Windows.Point Dim success As Boolean = True Return TryApplyVisualTransform(Point, v, inverse, True, success) End Function Private Function GetPixelOffset() As Windows.Point Dim pixelOffset As New Windows.Point() Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If ps IsNot Nothing Then Dim rootVisual As Visual = ps.RootVisual ' Transform (0,0) from this element up to pixels. pixelOffset = Me.TransformToAncestor(rootVisual).Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, False) pixelOffset = ps.CompositionTarget.TransformToDevice.Transform(pixelOffset) ' Round the origin to the nearest whole pixel. pixelOffset.X = Math.Round(pixelOffset.X) pixelOffset.Y = Math.Round(pixelOffset.Y) ' Transform the whole-pixel back to this element. pixelOffset = ps.CompositionTarget.TransformFromDevice.Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, True) pixelOffset = rootVisual.TransformToDescendant(Me).Transform(pixelOffset) End If Return pixelOffset End Function Private Function AreClose(ByVal Point1 As Windows.Point, ByVal Point2 As Windows.Point) As Boolean Return AreClose(Point1.X, Point2.X) AndAlso AreClose(Point1.Y, Point2.Y) End Function Private Function AreClose(ByVal value1 As Double, ByVal value2 As Double) As Boolean If value1 = value2 Then Return True End If Dim delta As Double = value1 - value2 Return ((delta < 0.00000153) AndAlso (delta > -0.00000153)) End Function End Class

    Read the article

  • CheckBox ListView SelectedValues DependencyProperty Binding

    - by Ristogod
    I am writing a custom control that is a ListView that has a CheckBox on each item in the ListView to indicate that item is Selected. I was able to do so with the following XAML. <ListView x:Class="CheckedListViewSample.CheckBoxListView" 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" mc:Ignorable="d"> <ListView.Style> <Style TargetType="{x:Type ListView}"> <Setter Property="SelectionMode" Value="Multiple" /> <Style.Resources> <Style TargetType="ListViewItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListViewItem"> <Border BorderThickness="{TemplateBinding Border.BorderThickness}" Padding="{TemplateBinding Control.Padding}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" SnapsToDevicePixels="True"> <CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"> <CheckBox.Content> <ContentPresenter Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> </CheckBox.Content> </CheckBox> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Style.Resources> </Style> </ListView.Style> </ListView> I however am trying to attempt one more feature. The ListView has a SelectedItems DependencyProperty that returns a collection of the Items that are checked. However, I need to implement a SelectedValues DependencyProperty. I also am implementing a SelectedValuesPath DependencyProperty. By using the SelectedValuesPath, I indicate the path where the values are found for each selected item. So if my items have an ID property, I can specify using the SelectedValuesPath property "ID". The SelectedValues property would then return a collection of ID values. I have this working also using this code in the code-behind: using System.Windows; using System.Windows.Controls; using System.ComponentModel; using System.Collections; using System.Collections.Generic; namespace CheckedListViewSample { /// <summary> /// Interaction logic for CheckBoxListView.xaml /// </summary> public partial class CheckBoxListView : ListView { public static DependencyProperty SelectedValuesPathProperty = DependencyProperty.Register("SelectedValuesPath", typeof(string), typeof(CheckBoxListView), new PropertyMetadata(string.Empty, null)); public static DependencyProperty SelectedValuesProperty = DependencyProperty.Register("SelectedValues", typeof(IList), typeof(CheckBoxListView), new PropertyMetadata(new List<object>(), null)); [Category("Appearance")] [Localizability(LocalizationCategory.NeverLocalize)] [Bindable(true)] public string SelectedValuesPath { get { return ((string)(base.GetValue(CheckBoxListView.SelectedValuesPathProperty))); } set { base.SetValue(CheckBoxListView.SelectedValuesPathProperty, value); } } [Bindable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Category("Appearance")] public IList SelectedValues { get { return ((IList)(base.GetValue(CheckBoxListView.SelectedValuesPathProperty))); } set { base.SetValue(CheckBoxListView.SelectedValuesPathProperty, value); } } public CheckBoxListView() : base() { InitializeComponent(); base.SelectionChanged += new SelectionChangedEventHandler(CheckBoxListView_SelectionChanged); } private void CheckBoxListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { List<object> values = new List<object>(); foreach (var item in SelectedItems) { if (string.IsNullOrWhiteSpace(SelectedValuesPath)) { values.Add(item); } else { try { values.Add(item.GetType().GetProperty(SelectedValuesPath).GetValue(item, null)); } catch { } } } base.SetValue(CheckBoxListView.SelectedValuesProperty, values); e.Handled = true; } } } My problem is that my binding only works one way right now. I'm having trouble trying to figure out how to implement my SelectedValues DependencyProperty so that I could Bind a Collection of values to it, and when the control is loaded, the CheckBoxes are checked with items that have values that correspond to the SelectedValues. I've considered using the PropertyChangedCallBack event, but can't quite figure out how I could write that to achieve my goal. I'm also unsure of how I find the correct ListViewItem to set it as Selected. And lastly, if I can find the ListViewItem and set it to be Selected, won't that fire my SelectionChanged event each time I set a ListViewItem to be Selected?

    Read the article

< Previous Page | 1 2 3 4 5