Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

wpf touchdown event using alot of cpu

$
0
0

Everytime i use touchdown event in a button/rectangle or whatever it uses a lot of cpu the more objects i touch. Is there another way to make an event happen only once when i touch a object because touchdown is doing something that is constantly using cpu while i hold down. In my program i need to make something happen once when i touch an object and do another thing once when i stop touching it, to be more exact its to make a boolean true and false. Anyway here is the code

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace sendString
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Stylus.SetIsPressAndHoldEnabled(this, false);

        }


        private const int GWL_EXSTYLE = -20;
        private const int WS_EX_NOACTIVATE = 0x08000000;

        [DllImport("user32.dll")]
        public static extern IntPtr SetWindowLong(IntPtr hWnd,

                                                  int nIndex,

                                                  int dwNewLong);

        [DllImport("user32.dll")]
        public static extern int GetWindowLong(IntPtr hWnd,

                                               int nIndex);


        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);



            //Set the window style to noactivate.
            WindowInteropHelper helper = new WindowInteropHelper(this);
            SetWindowLong(helper.Handle, GWL_EXSTYLE,
                GetWindowLong(helper.Handle, GWL_EXSTYLE) | WS_EX_NOACTIVATE);
        }








          private void Button_TouchDown(object sender, TouchEventArgs e)
          {

              Console.WriteLine("1111");
          }




          private void Button_TouchDown_1(object sender, TouchEventArgs e)
          {

              Console.WriteLine("22222");
          }


    }
}

<Window x:Class="sendString.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><Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="170" Height="79" Margin="190,0,0,0" TouchDown="Button_TouchDown"/><Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="185" Height="79" Margin="190,155,0,0" TouchDown="Button_TouchDown_1"/></Grid></Window>


Data trigger fill rectangle

$
0
0
Currently the trigger checks the "IsCurrent" property to fill the rectangle. Is there any way to fill rectangle / bold the header title without depends on"IsCurrent" property ? (maybe check header title ?)

WizardPage.xaml
<UserControl x:Class="TestProject.Wizard.WizardPage"
             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"
             xmlns:local="clr-namespace:TestProject.Wizard"
             xmlns:pageOne="clr-namespace:TestProject.PageOne"
             xmlns:pageTwo="clr-namespace:TestProject.PageTwo"
             xmlns:pageThree="clr-namespace:TestProject.PageThree"
             xmlns:common="clr-namespace:TestProject.Common"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300"><UserControl.Resources><DataTemplate DataType="{x:Type pageOne:PageOneViewModel}"><pageOne:PageOneView /></DataTemplate><DataTemplate DataType="{x:Type pageTwo:PageTwoViewModel}"><pageTwo:PageTwoView /></DataTemplate><DataTemplate DataType="{x:Type pageThree:PageThreeViewModel}"><pageThree:PageThreeView /></DataTemplate><DataTemplate x:Key="WizardMenuTemplate"><Grid Margin="5"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Path x:Name="path" Fill="Black" Data="M 0 4 L 4 0 L 8 4 Z" VerticalAlignment="Center" HorizontalAlignment="Center"><Path.RenderTransform><RotateTransform Angle="90"/></Path.RenderTransform></Path><TextBlock x:Name="header" Text="{Binding Title}" Width="80" TextAlignment="Center" Grid.Column="1" /><Rectangle x:Name="rect" Fill="Gray" Width="{Binding Path=ActualWidth, ElementName=header}" Height="3" Grid.Column="1" Grid.Row="1" /></Grid><DataTemplate.Triggers><DataTrigger Binding="{Binding IsCurrent}" Value="true"><Setter TargetName="header" Property="FontWeight" Value="Bold"/><Setter TargetName="rect" Property="Fill" Value="#2196f3"/><Setter TargetName="rect" Property="Height" Value="3.5"/></DataTrigger><DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}"><Setter Property="Visibility" TargetName="path" Value="Collapsed"/></DataTrigger></DataTemplate.Triggers></DataTemplate><ItemsPanelTemplate x:Key="panelTemplate"><StackPanel Orientation="Horizontal"  HorizontalAlignment="Right"/></ItemsPanelTemplate></UserControl.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="2*"/><RowDefinition Height="10"/><RowDefinition Height="6*"/><RowDefinition Height="10"/><RowDefinition Height="2*"/></Grid.RowDefinitions><!--WizardMenu--><HeaderedContentControl IsTabStop="False" HorizontalAlignment="Right"><ItemsControl ItemsSource="{Binding Pages}" ItemTemplate="{StaticResource WizardMenuTemplate}" ItemsPanel="{StaticResource panelTemplate}" IsTabStop="False" /></HeaderedContentControl><!--Content--><Border Grid.Row="2" BorderBrush="Gray" BorderThickness="1"><ContentControl Content="{Binding CurrentPage}" IsTabStop="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" /></Border><!--NavigationButton--><common:ActionView Grid.Row="4" DataContext="{Binding ButtonActions}" HorizontalAlignment="Right" IsTabStop="False" /></Grid></UserControl>

Download Project

Horizontal scrollbar in TreeView

$
0
0
Hello. I want to have only a horizontal scroll bar in TreeView which shows additional items not on the bottom but on the right side of TreeView(additional column of items). Is it feasible?

CallBack from one WPF window to parent WPF

$
0
0

I have a mainWindow that creates a new Window ("B") and the new "B" Window ( has 2 buttons ) Abort and Done. Both buttons close "B", but the mainWindow needs to know which button for the next operation. 

[ mainWindows] -> [ B window ]

Although there is a function in mainWindows to receive the string ..."ProcessCallBack (string foo)...

I have above MainWindow public delegate void MainWinDelegate(string foo);

at B  Public MainWinDelegate MyFuntion

And declare the delegate like MyFunction+=new MainWinDelegate( MainWindow.ProcessCallBack) but that gave an error saying it ( MainWindow ) an object reference is required for non static so I made the function ProcessCallBack static and it works.

However ->

I have also  looked at Application.Current.Dispatcher.BeginInvoke ( DispatcherPriority.Normal, new Action(()=>  but it only sees B's functions & properties.

The Dispatcher method seems like it might be a whole lot cleaner compared to what I did calling my own delegates.  If so does anyone have an example ??

Thanks you !  


andrew

Switching ContentControl Views seems to keep the instances active!

$
0
0

Hey, i'm going to provide the project here instead of show code as i'm not sure where the issue is occuring so not sure what to show. But basically I have got an ObservableCollection of Objects which define a View and it's ViewModel. However if I switch the content out in the ContentControl, the previous ViewModel seems to be instigated still. 

Currently in my OC List with the views I have about 4 duplicates which load the same view, once I build all the other views I obviously won't have these duplicates. But the first time the view is initiated it displays a message, now I thought if I load up a different view, the only one would be be forgotten and the instance of that view model and it's properties would be unloaded from memory, however it seems if I switch back to that same view, no message appears, so it's still in memory! 

This seems only to be an issue at the moment as a command seems to be trying to activate in all the views currently instigated. 

To reproduce the issue simply load the project, login using the following test details (removed database requirement), and then switch between the first 4 menu items, which load the LoginView, the bottom 2 load a different View. 

Download Here!

Add Views to App.xaml to access them globally.

$
0
0

Hey, I need to add my View ObservableCollection

ObservableCollection<ViewVM> views = new ObservableCollection<ViewVM>
            {
                new ViewVM { IconGeometry=App.Current.Resources["home4"] as Geometry, ViewDisplay="Home", ViewType = typeof(LoginView), ViewModelType = typeof(LoginViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["instagram3"] as Geometry, ViewDisplay="Images", ViewType = typeof(LoginView), ViewModelType = typeof(LoginView)},
                new ViewVM { IconGeometry=App.Current.Resources["money674"] as Geometry, ViewDisplay="Sales", ViewType = typeof(LoginView), ViewModelType = typeof(LoginViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["printing1"] as Geometry, ViewDisplay="Print Queue", ViewType = typeof(LoginView), ViewModelType = typeof(LoginViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["cog2"] as Geometry, ViewDisplay="Settings", ViewType = typeof(IconLibaryView), ViewModelType = typeof(IconLibaryViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["upload40"] as Geometry, ViewDisplay="Upload", ViewType = typeof(IconLibaryView), ViewModelType = typeof(IconLibaryViewModel)}
            };
            Views = views;
            RaisePropertyChanged("Views");
            views[0].NavigateExecute();


To an instance of the ObservableCollection within the App.xaml, this is because I need to be able to change the View at times when not in scope of the MainWindowViewModel, which is currently where the List is and binded. 

The plan is to simply add all the views to the Collection defined in XAML when the Application is booted up, which it does already but into a Collection defined in the MainWindowViewMode.

ObservableCollection<ViewVM> views = new ObservableCollection<ViewVM>
            {
                new ViewVM { IconGeometry=App.Current.Resources["home4"] as Geometry, ViewDisplay="Home", ViewType = typeof(LoginView), ViewModelType = typeof(LoginViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["instagram3"] as Geometry, ViewDisplay="Images", ViewType = typeof(LoginView), ViewModelType = typeof(LoginView)},
                new ViewVM { IconGeometry=App.Current.Resources["money674"] as Geometry, ViewDisplay="Sales", ViewType = typeof(LoginView), ViewModelType = typeof(LoginViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["printing1"] as Geometry, ViewDisplay="Print Queue", ViewType = typeof(LoginView), ViewModelType = typeof(LoginViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["cog2"] as Geometry, ViewDisplay="Settings", ViewType = typeof(IconLibaryView), ViewModelType = typeof(IconLibaryViewModel)},
                new ViewVM { IconGeometry=App.Current.Resources["upload40"] as Geometry, ViewDisplay="Upload", ViewType = typeof(IconLibaryView), ViewModelType = typeof(IconLibaryViewModel)}
            };
            ObservableCollection<ViewVM> Views = (ObservableCollection<ViewVM>)Application.Current.Resources["Views"];
            Views = views;
            RaisePropertyChanged("Views");
            views[0].NavigateExecute();


My current issue is creating a new ObservableCollection in the App.xaml

<coll:ObservableCollection x:Key="Views" />

Error:

The tag 'ObservableCollection' does not exist in XML namespace 'clr-namespace:System.Collections.ObjectModel;assembly=System'.

Obviously added the xmlns:coll="clr-namespace:System.Collections.ObjectModel;assembly=System"

Edit:

Just another thought, is it worth putting global things like this which I need to have in scope all of the time in the App.xaml.cs? Or is that not complying with MVVM? 

Calculate timespan acording to status

$
0
0

Hello. I need a little help, I cant see a solution for the moment.


I have a combobox with 2 values ONLINE and OFFLINE. I want to calculate timespan of ONLINE status.

For the moment I only calculate the difference between 2 date's but I am not sure how to do it acording to combobox selectedindex.

I know that when DropDownClosed I should stop or start the timer acording to selectedIndex, but I am stuck when I need to calculate the new elapsedtime. Can you please help me?


// Date and time when a user login (status ONLINE)
public DateTime LoginDate = DateTime.Now;
public DateTime WorkedTime = DateTime.Now;

 private void SetTimer()
 {
     dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        dispatcherTimer.Start();
}

        protected void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            interval = WorkedTime;- WorkedTime;
            string intervalInWords = String.Format("{0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds", interval);
            this.tb_ElapsedTime.Text = tb_ElapsedTime.Text intervalInWords;


        }


XamlWriter.Save doesnt parse Button children

$
0
0

 got a dynamic WPF view and i create my controls programmatically. The problem is, I got a button control, which has a trigger event.

<ButtonName="myButton"Command="{Binding myCommand}"xmlns:namespace....><i:Interaction.Triggers><i:EventTriggerEventName="SomethingChanged"SourceObject="{Binding}"><i:SomeAction/></i:EventTrigger></i:Interaction.Triggers></Button>

If I write the code hard-coded, it works fine. If I use XamlParser, it only parse the following

<ButtonName="myButton"Command="{Binding myCommand}"xmlns:namespaces....></Button>

I put all the relevant namespaces inside the button, but no help. Is there a solution for using XamlParser? Is there another way to parse the button programmatically?

Thanks in advance.


Windows 7 like style for WPF?

$
0
0

Hi ~ I'm trying to make an application in WPF that looks like Photoshop or Google Chrome. But I'm using WPF and Windows 10. Is there any styles or anything to make it look like these programs or how could I make my own style to look like them? Thanks a million!

PS: sorry if im ambiguous.. Idk how to ask this correctly

Also look up 'photshop ui' too see what I mean :)

Animate the changing of my ContentControl.

$
0
0
I want to have my ContentControl animate, for example the content fade in/out or maybe swipe in/out. What is the best way to do this? I have found the following tutorial, is this a good way to do this? 

Project Centennial status?

$
0
0

Hey guys, perhaps I'm behind the ball on this one but I can't seem to find any actual information on Project Centennial beyond that 'it exists.' My company is really looking into a Win32 bridge so that we can use telnet apps like PuTTY which the store currently has nothing that quite handles what we're looking for. The most promising candidate went in to open beta than fell off the face of the earth, and won't respond to emails about the application.

Alternately, if anyone out there wants to work on an open source telnet client, I'm all ears! :)

[WPF] Implement a Windows Forms designer

$
0
0

Hi,

I want to achieve a Windows Forms designer like embbed in a WPF MVVM application. Major part of tutorials in the web talks only how to do this in a Windows Forms app.

The goal of my project is not to generate WinForm code but only implement a similar designer, i just search for tracks.

Thanks a lot for your help

Regards

C# WPF InkCanvas - Cursor jump

$
0
0

I'm writing drawing application using C# WPF InkCanvas. Problem is, When I set UseCustomCursor = "True", and Cursor = "Hand", the cursor on InkCanvas jumps to the first point of a stroke. Not all times but sometimes. Not on mouse movement, but on stylus movement.

Code here.

<Window x:Class="CursorJump.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:CursorJump"
        mc:Ignorable="d"
        Title="CursorJump" Height="350" Width="525"><Grid><InkCanvas UseCustomCursor="True" Cursor="Hand" ><InkCanvas.DefaultDrawingAttributes><DrawingAttributes
                    Height="3"
                    Width="3"
                    Color="SlateGray"/></InkCanvas.DefaultDrawingAttributes></InkCanvas></Grid></Window>


So I researched MSDN and stackoverflow. All I found is the fact that WPF have diffrent two or more rendering thread: dynamic rendering thread and UI thread. 

As the user draws a stroke, DynamicRenderer renders the ink on a separate thread so the ink appears to "flow" from the pen even when the UI thread is busy. The DynamicRenderer builds a visual tree on the dynamic rendering thread as it collects stylus points. When the user finishes the stroke, the DynamicRenderer asks to be notified when the application does the next rendering pass. After the application completes the next rendering pass, the DynamicRenderer cleans up its visual tree. The following diagram illustrates this process.

I think the ink threading model causes this abnormal 'cursor jump' phenomenon. As stylus moves, Hand cursor follows stylus raw input point (in dynamic rendering thread) and when stylus input fragment is processe to stroke, my Hand cursor jump to starting point of the stroke(in UI thread).

Am I right? if then, How could I fix this problem?


Get caption/song title of audio stream in a media player object

$
0
0

Hello!

I have an application that uses the media player object to stream music from a internet radio station.

When i use other media players like VLC or Windows Media Player, they display the song title or caption when available by the radio station. 

I found this thread over at StackOverflow that used amedia element object and it was also in Silverlight, so i don't know if that can give us any clue. That method resolves the caption separately using the System.Web.HttpUtility.UrlDecode method.

I prefer vb.net but C# works fine too.

Thanks for all help!


Combobox caret position

$
0
0

The combox cursor position doesn't change with the text when i am typing the new text. To handle this i did the code behind:

  private void MyComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox MyCombo = sender as ComboBox;

            if (MyCombo != null)
            {
                TextBox text = MyCombo.Template.FindName("PART_EditableTextBox", MyCombo) as TextBox;

                if (null != text)
                {
                    text.Select(text.Text.Length, 0);
                }
            }

        }

But the selection changed is not triggered when entering the new text. The same is happening with comobobox textInput event.

Combobx xaml:

<cls:MyComboBox FontSize="13"
                      IsEditable="True"
                      Margin="2,0,2,5"
                      Text="{Binding MyData}"
                      ItemsSource="{Binding Path=MyNumbers}"
                      SelectedValuePath="Number"
                      SelectedValue="{Binding Path=MyData}"
                      ItemTemplate="{StaticResource MyTemplate}"
                      Width="175"
                      Name="QuickDialComboBox"
                      Grid.Column="0"
                      SelectionChanged="MyComboBox_SelectionChanged"></MyComboBox><DataTemplate x:Key="MyTemplate"><StackPanel Name="ItemContainer" Background="{Binding Path=Background}" HorizontalAlignment="Stretch" MaxWidth="200"><TextBlock Text="{Binding MyItem, StringFormat='\{0\}                              '}"
                           Foreground="{Binding Path=Foreground}" TextWrapping="NoWrap" Margin="10,0,0,0" MaxWidth="200"/></StackPanel></DataTemplate>




WPF textbox problem

$
0
0

I have a textbox that is prepopulated with some data.  Is there a way I can highlight the data upon entry and allow the operator to wipe the previous entry withone keystroke and type something new?


Certified Geek

Reference instance of class and fill ListView with it's Property

$
0
0

My extended contentcontrol doesn't seem to be getting any content, below is it's markup.

<Controls:AnimatedContentControl Content="{StaticResource CurrentView}" Grid.Row="1" Grid.Column="1" />

And this is the Style:

<Style TargetType="{x:Type Controls:AnimatedContentControl}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Controls:AnimatedContentControl}"><Grid><ContentPresenter Content="{TemplateBinding Content}" x:Name="PART_MainContent" /><Rectangle x:Name="PART_PaintArea" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /></Grid></ControlTemplate></Setter.Value></Setter></Style>

This is the StaticResource

<local:ViewChange x:Key="CurrentView" />

And below of course is the class which the StaticResource is an instance off

namespace PhotoManagement
{
    public class ViewChange : Common.NotifyUIBase
    {
        private NavigateMessage _v;
        public NavigateMessage V
        {
            get { return _v; }
            set
            {
                if (_v != value)
                {
                    _v = value;
                    RaisePropertyChanged();
                }
            }
        }
    }
}

This Instance is then updated like so:

var msg = new NavigateMessage { View = View, ViewModelType = ViewModelType, ViewType = ViewType };

//Replace XAML Instance with new View
((ViewChange)Application.Current.Resources["CurrentView"]).V = msg;

I believe my ViewChange class is created incorrectly, as the Content call will not know to look within the V property, how do I fix this? I have attempted

{StaticResource CurrentView.V}

However this causes this error

The resource "CurrentView.V" could not be resolved.

WPF DataGridCheckBox check/uncheck doesn't work well

$
0
0

I have a DataGridCheckBox column bound to a field in DB. The issue is that sometimes the check/uncheck works right away, and sometimes it doesn't, even if I click many times, the click won't stay. In these cases, the only thing that solves this is clicking the CheckBox, and while mouse down, dragging to next field and leave mouse. This way the checked/uncheck stays fine...

This is the code:

DataGridCheckBoxColumn x:Name="to_send"Binding="{Binding to_send, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"Width="150"Header="To Send ?"IsThreeState="False"ElementStyle="{StaticResource {x:Type CheckBox}}"

Any ideas how to solve this ?

Thanks, Ronit.


Problem with setting Selected Item of a Combo Box

$
0
0

I have a Combo Box on a MVVM control.  I am going to set the Selected Item and it is not taking.  I have made sure the data types of the item are the same, it is a custom data type.  

I set the Selected Item property for the Combo Box directly and it will simply not pick it up.  

Any thoughts to this weird issue would be greatly appreciated.


Robert Johnston

the best way to make UI on WPF?

$
0
0

hi

i need to make a good UI on WPF c# .net 4.5/4.6 and i know photoshop.

can i make my xmal on photoshop?

reuven

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>