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

How draw custom shape with inkcanvas

$
0
0

I want to draw line or rectangle by Inkcanvas .I draw rectangle with custom render. The problem is there are many rectangles drawn when mouse moving.This is my code.

  class CustomDynamicRenderer : DynamicRenderer
    {
        [ThreadStatic]
        static private Brush brush = null;

        [ThreadStatic]
        static private Pen pen = null;

        private Point prevPoint;
        bool first;

        protected override void OnStylusDown(RawStylusInput rawStylusInput)
        {
            // Allocate memory to store the previous point to draw from.
            prevPoint = new Point(double.NegativeInfinity, double.NegativeInfinity);
            base.OnStylusDown(rawStylusInput);
            
        }

        protected override void OnStylusUp(RawStylusInput rawStylusInput)
        {
            first = false;
            base.OnStylusUp(rawStylusInput);
        }

        protected override void OnDraw(DrawingContext drawingContext,
                                       StylusPointCollection stylusPoints,
                                       Geometry geometry, Brush fillBrush)
        {
            // Create a new Brush, if necessary.
            if (brush == null)
            {
                brush = new LinearGradientBrush(Colors.Red, Colors.Blue, 20d);
            }

            // Create a new Pen, if necessary.
            if (pen == null)
            {
                pen = new Pen(brush, 2d);
            }

            if (!first)
            {
                prevPoint=(Point)stylusPoints[0];
                first = true;
            }

            drawingContext.DrawRectangle(null, pen,  new Rect(prevPoint,(Point)stylusPoints[stylusPoints.Count-1]));
          
        }
    }


Hierarchical data tempate doesn't work.

$
0
0

hello. I'm trying to use Hierarchical data template for treeview but it doesn't work for some reason.

public class ViewModel
    {
        private name;
        public ViewModel(string name)
        {
            this.name = name;
            Children = new ObservableCollection<ViewModel>();
            Children.Add("1");
            Children.Add("2");
        }

        public string Name => name;

        public ObservableCollection<ViewModel> Children { get; }
    }

<TreeView x:Name="Tree" Grid.Row="1"><TreeView.ItemTemplate><HierarchicalDataTemplate ItemsSource="{Binding Path=Children}"><TextBlock Text="{Binding Path=Name}" /></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView>

Binding is definitely working because I can create TreeItem and bind the name to it but I don't see any items in case of this template.


WP 8.1 Play Audio across pages

$
0
0

Hi

I am trying to run Audio File across pages 

In App.xaml

<Application    x:Class="Test1.App"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:local="using:Test1">    <Application.Resources>        <MediaElement x:Name="myMediaElement" Source="Assets/angry.mp3" AutoPlay="False" HorizontalAlignment="Left" Height="103" Margin="98,56,0,0" VerticalAlignment="Top" Width="255" />    </Application.Resources></Application>

In App.xaml.cs

using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.ApplicationModel;using Windows.ApplicationModel.Activation;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Media.Animation;using Windows.UI.Xaml.Navigation;// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641namespace Test1{    /// <summary>    /// Provides application-specific behavior to supplement the default Application class.    /// </summary>    ///     public sealed partial class App : Application    {        private TransitionCollection transitions;               /// <summary>        /// Initializes the singleton application object.  This is the first line of authored code        /// executed, and as such is the logical equivalent of main() or WinMain().        /// </summary>        ///         public static MediaElement GlobalMediaElement        {            get { return Current.Resources["myMediaElement"] as MediaElement; }        }        public App()        {            this.InitializeComponent();            this.Suspending += this.OnSuspending;                    }        public void Play()        {          //  var AppMediaElement = Current.Resources["myMediaElement"] as MediaElement;            //set the source           //GlobalMediaElement.Source = new Uri("ms-appx:///Assets/angry.mp3", UriKind.RelativeOrAbsolute);            //set the timespan            //GlobalMediaElement.Position = TimeSpan.Zero;            //set the autoplay            //GlobalMediaElement.AutoPlay = true;                        //play the file            GlobalMediaElement.Play();            Debug.WriteLine("The status is " + GlobalMediaElement.CurrentState);        }        /// <summary>        /// Invoked when the application is launched normally by the end user.  Other entry points        /// will be used when the application is launched to open a specific file, to display        /// search results, and so forth.        /// </summary>        /// <param name="e">Details about the launch request and process.</param>        protected override void OnLaunched(LaunchActivatedEventArgs e)        {#if DEBUG            if (System.Diagnostics.Debugger.IsAttached)            {                this.DebugSettings.EnableFrameRateCounter = true;            }#endif            Frame rootFrame = Window.Current.Content as Frame;            // Do not repeat app initialization when the Window already has content,            // just ensure that the window is active            if (rootFrame == null)            {                // Create a Frame to act as the navigation context and navigate to the first page                rootFrame = new Frame();                // TODO: change this value to a cache size that is appropriate for your application                rootFrame.CacheSize = 1;                // Set the default language                rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)                {                    // TODO: Load state from previously suspended application                }                // Place the frame in the current Window                Window.Current.Content = rootFrame;            }            if (rootFrame.Content == null)            {                // Removes the turnstile navigation for startup.                if (rootFrame.ContentTransitions != null)                {                    this.transitions = new TransitionCollection();                    foreach (var c in rootFrame.ContentTransitions)                    {                        this.transitions.Add(c);                    }                }                rootFrame.ContentTransitions = null;                rootFrame.Navigated += this.RootFrame_FirstNavigated;                // When the navigation stack isn't restored navigate to the first page,                // configuring the new page by passing required information as a navigation                // parameter                if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))                {                    throw new Exception("Failed to create initial page");                }            }            // Ensure the current window is active            Window.Current.Activate();            Play();        }        /// <summary>        /// Restores the content transitions after the app has launched.        /// </summary>        /// <param name="sender">The object where the handler is attached.</param>        /// <param name="e">Details about the navigation event.</param>        private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)        {            var rootFrame = sender as Frame;            rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };            rootFrame.Navigated -= this.RootFrame_FirstNavigated;        }        /// <summary>        /// Invoked when application execution is being suspended.  Application state is saved        /// without knowing whether the application will be terminated or resumed with the contents        /// of memory still intact.        /// </summary>        /// <param name="sender">The source of the suspend request.</param>        /// <param name="e">Details about the suspend request.</param>        private void OnSuspending(object sender, SuspendingEventArgs e)        {            var deferral = e.SuspendingOperation.GetDeferral();            // TODO: Save application state and stop any background activity            deferral.Complete();        }    }}

In MusicPage.xaml.cs

using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556namespace Test1{    /// <summary>    /// An empty page that can be used on its own or navigated to within a Frame.    /// </summary>    public sealed partial class MusicPage : Page    {                public MusicPage()        {            this.InitializeComponent();            //MediaElement myMediaElement = new MediaElement();            //   var AppMediaElement = App.GlobalMediaElement as MediaElement;            //set the source            //  App.GlobalMediaElement.Source = new Uri("ms-appx:///Assets/angry.mp3", UriKind.RelativeOrAbsolute);            //set the timespan            //    App.GlobalMediaElement.Position = TimeSpan.Zero;            //set the autoplay            //    App.GlobalMediaElement.AutoPlay = true;            //play the filer            MediaElement mediaElement1 = new MediaElement();            mediaElement1.Source = new Uri("ms-appx:///Assets/angry.mp3", UriKind.RelativeOrAbsolute);            mediaElement1.AutoPlay = false;            mediaElement1.Play();                        // Add the MediaElement to the page.            //App.Children.Add(mediaElement1);           /* App.GlobalMediaElement.Source = new Uri("ms-appx:///Assets/angry.mp3", UriKind.RelativeOrAbsolute);            Debug.WriteLine("The Source is " + App.GlobalMediaElement.Source);            App.GlobalMediaElement.AutoPlay = true;            App.GlobalMediaElement.Play();*/        }                   /// <summary>        /// Invoked when this page is about to be displayed in a Frame.        /// </summary>        /// <param name="e">Event data that describes how this page was reached.        /// This parameter is typically used to configure the page.</param>        protected override void OnNavigatedTo(NavigationEventArgs e)        {            //Taking the Parameter recieved by NavigationEventArgs e              // paramTextBlock.Text = e.Parameter.ToString();              //creating a var type variable and save the object parameter from page 1              //and typecasting it with the Class we have created              var name = e.Parameter.ToString();            if (!string.IsNullOrWhiteSpace(name))            {                musicBox.Text = "Hello, " + name;            }            else            {                musicBox.Text = "Name is required.  Go back and enter a name.";            }        }        private void on_backButton(object sender, RoutedEventArgs e)        {            this.Frame.GoBack();            // NavigationService.Navigate(new Uri("/MusicPage.xaml?msg=" + textBox.Text, UriKind.Relative));        }        private class LoadStateEventArgs        {        }    }}

Now with this music file is not playing .

Rg

Phoneme


TextBox, working with currency or decimal

$
0
0

Hello Everyone!

I need to work with currency in my app. I need a way to validate the values in currency formats like:
"23,00"
"234,89"
"1000,00"

But I don't know how could I do that.
I was thinking about using a maskedtextbox, but didn't work at this point.

So, how could I set a textbox to do that?


Valdirnm

UI That Fits All Screen Sizes

$
0
0

Hi,

I am looking for some help on what the best practices are for creating a UI which fits all screen sizes. I've been searching online for some information about this but it seems very difficult to collect information about this as there doesn't seem to be any kind of general answer.

I am creating a UI which is going to have draggable tabs (the tabs are going to be attached to panels) which can be dragged around the interface and docked in certain places. There will be a menu header as well very generic (File, Edit, etc).

I've been reading and watching some videos on how to master the Grid element and was wondering if this would be the best element to use, I am guessing I could use it as intended and split up my screen in to it's interface sections and work within those grid definitions to place my other elements.

Also I wanted to know a little bit more about the window width and height, if I set those values to a specific width and height what would they be used for? Would that be the size of my window when the window isn't maximized to the users screen size? How would I make my window fit all screen sizes without covering the taskbar? I tried System.Windows.SystemParameters.PrimaryScreenWidth and same for the height too, I put this in my code behind under the Initialize() method within my MainWindow.cs and I can still see that the window overlaps behind the taskbar and doesn't line up with the taskbar.



C# Application/Device Comunication Solution

$
0
0

Hello,

I am looking for the best solution to tackle the type of application/device communication that I am looking for. Here is an outline of what communication I want...

1. A WPF application that is both a server and a client

2. User enters a local IP of the computer with another of the app running to connect to

3. Can send and receive commands between systems/applications (Ex. Tell application running at machine 192.168.0.32 to report CPU usage % of that machine)

Some have said Windows Communication Foundation is solution but I don't want a web server needed, I was going to just use TCP/IP and send text commands that the client listens for but it seems like a crude solution.

Any advice is welcome,

Cheers!

Demo of Interface and Abstract Example impliment in MVVM projcet

$
0
0

hi to all,

Please can you tell me , How to implement Interface and Abstract class in MVVM project . Please give me a specific demo.

Thanks,



A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Interface and Abstract implementation in MVVM project

$
0
0

hi to all,

Please can you tell me , How to implement Interface and Abstract class in MVVM project . Please give me a specific demo.

Thanks,


A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.


how to control denpencty properties changed order

$
0
0
I  create a usercontrol which have two dependency properties.I do some pocesses   when the denpendency properties changed by data binding.My problem is that I don't know when the A property is changed first or the B property is changed  first.

Exception Error in richtextbox.CaretPosition.GetCharacterRect when typing with non english language and Italic style

$
0
0

I am developing editor with RichTextBox under .Net 3.5 WPF environment VS2013 Ultimate Update 4 and VS2015 Community Update 3.

I need to check screen position of current caret position and scroll automatically scroller when I type any text.

code is here.

        private void Italicbtn_Click(object sender, RoutedEventArgs e)
        {
            editorctrl.SetFontProperties(richtextbox1, TextElement.FontStyleProperty, FontStyles.Italic);
            richtextbox1.Focus();
        }

        private void Richtextbox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            Rect r = GetCurrentCaretPos();

            // scroller down
            //if (rect.Y > 400)
            //{
            //    scroller1.LineDown();
            //}
        }

        public Rect GetCurrentCaretPos()
        {
            Rect rect = richtextbox1.CaretPosition.GetCharacterRect(LogicalDirection.Backward);
            Debug.WriteLine(String.Format("CaretPos : {0} {1}", rect.X, rect.Y));

            return rect;
        }

typing language is non-english, Hangul korea.

If I type without Italic style, it's fine even if I type slow with Italic style.

But If I type a little fast with Italic style, Sample Application just shutdowns on VS2015.

My real Project with same Logic has System.ExecutionEngineException on VS2013.

Below is error stacks.

How can I fix it?

> WindowsBase.dll!MS.Internal.Invariant.FailFast(string message, string detailMessage) 알 수 없음
  WindowsBase.dll!MS.Internal.Invariant.Assert(bool condition, string invariantMessage) 알 수 없음
  PresentationFramework.dll!System.Windows.Documents.CaretElement.OnRenderCaretSubElement(System.Windows.Media.DrawingContext context) 알 수 없음
  PresentationFramework.dll!System.Windows.Documents.CaretElement.CaretSubElement.OnRender(System.Windows.Media.DrawingContext drawingContext) 알 수 없음
  PresentationCore.dll!System.Windows.UIElement.Arrange(System.Windows.Rect finalRect) 알 수 없음
  PresentationFramework.dll!System.Windows.Documents.CaretElement.ArrangeOverride(System.Windows.Size availableSize) 알 수 없음
  PresentationFramework.dll!System.Windows.FrameworkElement.ArrangeCore(System.Windows.Rect finalRect) 알 수 없음
  PresentationCore.dll!System.Windows.UIElement.Arrange(System.Windows.Rect finalRect) 알 수 없음
  PresentationFramework.dll!System.Windows.Documents.AdornerLayer.ArrangeOverride(System.Windows.Size finalSize) 알 수 없음
  PresentationFramework.dll!System.Windows.FrameworkElement.ArrangeCore(System.Windows.Rect finalRect) 알 수 없음
  PresentationCore.dll!System.Windows.UIElement.Arrange(System.Windows.Rect finalRect) 알 수 없음
  PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayout() 알 수 없음
  PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayoutCallback(object arg) 알 수 없음
  PresentationCore.dll!System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork() 알 수 없음
  PresentationCore.dll!System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() 알 수 없음
  PresentationCore.dll!System.Windows.Media.MediaContext.RenderMessageHandlerCore(object resizedCompositionTarget) 알 수 없음
  PresentationCore.dll!System.Windows.Media.MediaContext.RenderMessageHandler(object resizedCompositionTarget) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, bool isSingleParameter) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl() 알 수 없음
  WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(object state) 알 수 없음
  mscorlib.dll!System.Threading.ExecutionContext.runTryCode(object userData) 알 수 없음
  [native에서 managed로 전환]
  mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) 알 수 없음
  mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke() 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue() 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) 알 수 없음
  WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) 알 수 없음
  WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, bool isSingleParameter) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.InvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, bool isSingleParameter) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority priority, System.Delegate method, object arg) 알 수 없음
  WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) 알 수 없음
  [native에서 managed로 전환]
  [managed에서 native로 전환]
  WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) 알 수 없음
  WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() 알 수 없음
  PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) 알 수 없음
  PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) 알 수 없음
  PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) 알 수 없음
  PresentationFramework.dll!System.Windows.Application.Run() 알 수 없음

Manually Re-center/Move A Window After Its Initial Width and Height Have Changed

$
0
0
In my app I have a WPF window with several controls that automatically size to content. The window's startup location is set to "CenterScreen", and when it initially loads it is at center screen. But when content is loaded sometimes it becomes very large. And so I need to plant some code that will manually recenter it.

I have calculated and set Window.Top and Window.Left and then tried messing around with InvalidateMeasure(), UpdateLayout(), Show(), Hide(), Activate(). But none of these actually moves the window to the center of the screen. In fact, none of them ever move the window at all, period.

What am I missing here? This should be a pretty easy thing to do, right?

XamlReader.Parse will not work with none ascii characters

$
0
0

XamlReader.Parse(string, parseContext) creates a MemoryStream with default codepage, but when the XmlReader is created no encoding is given. XmlReader will use utf8 as default.

Every Xaml-String that contains none ascii characters will crash!

btw. why is there no Load(XmlReader, ParserContext)-Overload?

WPF center screen issues

$
0
0

I have my WPF design as follows

<Window
        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:WPFApp1"
        xmlns:Usercontrols="clr-namespace:WPFApp1.Usercontrols" x:Class="WPFApp1.Window1"
        mc:Ignorable="d"
        Title="Window1" Width="763" Height="950" ResizeMode="NoResize" Loaded="Window_Loaded"><Grid Height="224" Width="Auto"><CheckBox x:Name="Checkbox1" Width="100px" Height="25px" Content="Checkbox" Margin="90,-120,567,319"/><CheckBox x:Name="Checkbox2" Height="25px" Content="Checkbox1"  Margin="178,-120,457,319"/><CheckBox x:Name="Checkbox3" Width="Auto" Content="Checkbox2"  Margin="296,-120,309,319"/><CheckBox x:Name="Checkbox4" Width="Auto" Content="Checkbox3"  Margin="420,-120,213,319"/><GroupBox Name="grp1" Header="Group1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="92,56,0,98" Width="590" Height="70" IsEnabled="False"></GroupBox><GroupBox Name="grp2" Header="Group2" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="92,136,0,18" Width="590" Height="70" IsEnabled="False"></GroupBox></Grid></Window>  

Here is the link of my exe which is developed , in my laptop header is not getting visible but where as in my desktop I am able to see it clearly

http://www.c-sharpcorner.com/forums/uploadfile/2cd341/11022016063754AM/testwpf.zip

Does this bug fixed in VS2015?--------"window-targettype-does-not-match-type-of-element-windowinstance"

$
0
0

It seems that this bug still exits in VS2015, hoping for better solution.

https://connect.microsoft.com/VisualStudio/feedback/details/610152/window-targettype-does-not-match-type-of-element-windowinstance

DataTemplateSelector MVVM

$
0
0

Hi,

I'm trying to write a template selector that let the user define the selection logic in XAML.

For example, the user define an ItemsControl and wants to define that if the one of the items' type is int32, select the template MyInt32Template.

<ItemsControl ItemsSource="{Binding MyList}"><ItemsControl.Resources><DataTemplate x:Key="MyInt32Template" DataType="{x:Type sys:Int32}"><TextBox Text="{Binding Path=.}"></TextBox></DataTemplate></ItemsControl.Resources><mycode:TemplateSelectorBehavior.Collection><mycode:SelectionParameter type="{x:Type sys:Int32}" DataTemplate="{StaticResource MyInt32Template}" /></mycode:TemplateSelectorBehavior.Collection><ItemsControl.ItemTemplateSelector><mycode:TemplateSelectorBehavior></mycode:TemplateSelectorBehavior></ItemsControl.ItemTemplateSelector></ItemsControl>

The TemplateSelectorBehavior, test the type of the object 'item' in its SelectTemplate(object item, DependencencyObject container), and if its the same, return the SelectionParameter.DataTemplate.

This works fine.

Now, I want to let the user define a way to  select the template by checking the value of a specific property of the current item.

For example, if item.MyValue == 1, select the template MyInt32Template

<mycode:SelectionParameter PropertyName="MyValue" PropertyValue="1" DataTemplate="{StaticResource MyInt32Template}"/>

This also works fine.

But what if I want to bind a dynamic value to the 'PropertyValue'?

SelectionParameter.PropertyValue property is a DependencyProperty so writing PropertyValue={Binding} compiles and run.

The propblem is that {Binding} return null.

My question is, how do I support binding to at least the parent control (the ItemsControl), maybe by using RelativeSource etc...

BTW, writing {Binding Path=. RelativeSource={RelativeSource Self} does return the SelectionParameter object.

Here is the code so far:

    public class TemplateSelectorBehavior : DataTemplateSelector
    {
        public static readonly DependencyProperty CollectionProperty =
           DependencyProperty.RegisterAttached("Collection", typeof(SelectionParameterCollection), typeof(TemplateSelectorBehavior),
            new FrameworkPropertyMetadata(new SelectionParameterCollection()));

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            SelectionParameterCollection coll = GetCollection(container);
            if (coll == null)
                return null;

            object itemToCheck = item;

            foreach (var param in coll)
            {

                // check type
                if (param.type != null && param.type == itemToCheck.GetType())
                    return param.DataTemplate;

                // check c# property
                if (!string.IsNullOrEmpty(param.PropertyName) && param.PropertyValue != null)
                {
                    PropertyInfo pi = itemToCheck.GetType().GetProperty(param.PropertyName);
                    if (pi != null)
                    {
                        if (pi.CanRead)
                        {
                            try
                            {
                                object propValue = Convert.ChangeType(param.PropertyValue, pi.PropertyType);

                                // compare
                                if (object.Equals(pi.GetValue(itemToCheck), propValue))
                                    return param.DataTemplate;
                            }
                            catch (Exception) { }
                        }
                    }
                }
            }

            return null;
        }
    }


    public class SelectionParameterCollection : List<SelectionParameter>
    {
    }

    public class SelectionParameter : DependencyObject
    {
        public DataTemplate DataTemplate { get; set; }

        /// <summary>
        /// The type of the object that should show the DataTemplate
        /// </summary>
        public Type type { get; set; }

        /// <summary>
        /// If the object has a property named 'PropertyName' and the property
        /// value is 'PropertyValue', than show the DataTemplate
        /// </summary>
        public string PropertyName { get; set; }

        public static readonly DependencyProperty PropertyValueProperty =
            DependencyProperty.Register("PropertyValue", typeof(object), typeof(SelectionParameter));
        public object PropertyValue { get { return (object)GetValue(PropertyValueProperty); } set { SetValue(PropertyValueProperty, value); } }
    }


WPF Application not running without Visual Studio.

$
0
0

Hi Team,

I have developed a WPF project in .Net 4.6 framework. I had tried to install the application in Windows 7 and Windows 8 VMs without Visual Studio. I was not able run the application even though I had already installed the .Net 5.6 frameworks. The application was crashing while opening. Hence to debug the issue, VS2015 was installed in both the VMs (fresh VMs). I reinstalled our application in the VMs, Then the issue gets rid off. Now, I have not installed the 4.6 Frameworks separately.

Could anyone suggest me why the application behavior was different with and without VS2015 and how can I overcome the above issue in machines without Visual Studio installed?

Kindly share your ideas.

Regards,

Amresh S.

Double click an video or audio file and have it open in my WPF mediaelement ?

$
0
0

Hi
I create a media player using wpf.
But I can not associate file type on my project.
Please tell me how can I declare ?

I see some question here but I am not understood.

Please anybody tell me how can I solve this problem.

How can I add file types on my wpf project and double click those files & have it open in my mediaelement.

Like this.

Its working open with .
When I double click video file & open it's on KMPlayer.

But how can I add this process on my wpf media player project?


Sabbir Ahmed

How to discern the means of focus change

$
0
0

Hi all. This is a WPF question, and I hope this is the right place to ask it.

When a UIElement receives the keyboard focus, it generates a GotKeyboardFocus event I can subscribe to. My question is, what is the best way to know *how* focus got there. Specifically, I'd like to know if the focus arrived by a keyboard operation (such as a tab key, access key, or accelerator key) or by some other means (such as a tap or click) so I can discern between a keyboard user and a mouse user for UI purposes.

Looking at the documentation for  KeyboardFocusChangedEventArgs (the event argument class for the GotKeyboardFocus event), I got the impression I could use the type of the object returned by the Device property. However, whether the focus changed via tab key or mouse click, this property always returns a KeyboardDevice object--not a MouseDevice object. Examining the keyboard state is not ideal because there are so many ways a keyboard can be used to move focus.


System.Windows.Controls.DataVisualization lineseiries swapping their positions

$
0
0

I have 2 line serieses

 <ChartingTool:Chart Name="myChart" Width="600" Height="350">
                <ChartingTool:Chart.Series>
                    <ChartingTool:LineSeries Name="lineseries1" ItemsSource="{Binding PlotDataList}" IndependentValueBinding="{Binding Volume}" DependentValuePath="Param1" Title="Param1">
                        <ChartingTool:LineSeries.IndependentAxis>
                            <ChartingTool:LinearAxis Orientation="X"  Title="Vol%" Minimum="0" Interval="20" />
                        </ChartingTool:LineSeries.IndependentAxis>
                        <ChartingTool:LineSeries.DependentRangeAxis>
                            <ChartingTool:LinearAxis Orientation="Y" Title="Param1" />
                        </ChartingTool:LineSeries.DependentRangeAxis>
                    </ChartingTool:LineSeries>
                    <ChartingTool:LineSeries Name="lineseries2" ItemsSource="{Binding PlotDataList}" IndependentValueBinding="{Binding Volume}" DependentValuePath="Param2" Title="Param2">
                        <ChartingTool:LineSeries.DependentRangeAxis>
                            <ChartingTool:LinearAxis Orientation="Y" Title="Param2" />
                        </ChartingTool:LineSeries.DependentRangeAxis>
                    </ChartingTool:LineSeries>
                </ChartingTool:Chart.Series>
            </ChartingTool:Chart>

1st time the chart is not coming properly, the 2nd line series is coming left side and 1st one is coming or right side of the chart as shown in below image. 

but when i revisit the form it comes correctly..

I am not able to find what makes first time that param1 gets in right side.

Please help how to solve this.

Thank You!!!

Sai Prashad

Exception thrown at 0x77CBE43E (ntdll.dll) in project.exe: 0xC0000005: Access violation reading location 0x7F498A38.

$
0
0

We build a WPF application using VS 2015 and access database engine 2007. When debug it, we got error like "Exception thrown at 0x77CBE43E (ntdll.dll) in project.exe: 0xC0000005: Access violation reading location 0x7F498A38.". the error happened on the following line of code:

dataadapter.Fill(datatable)

This line of code is in a public function and is being called many times, but sometimes the error happened but not always. The information on Call Stack like below.  I have been working on this error for a couple of days but still has no clues to fix it.

Any help will be much appreciated. Thanks.

     ntdll.dll!@RtlpLowFragHeapFree@8()    Unknown
     ntdll.dll!_RtlFreeHeap@12()    Unknown
     KernelBase.dll!_LocalFree@4()    Unknown
     cryptsp.dll!_CryptDestroyKey@4()    Unknown
     MSO.DLL!32fecf1c()    Unknown
     [Frames below may be incorrect and/or missing, no symbols loaded for MSO.DLL]    
     ACECORE.DLL!33ffcc80()    Unknown
     ACEOLEDB.DLL!33bd49f4()    Unknown
     ACEOLEDB.DLL!33bc3660()    Unknown
     ACECORE.DLL!33f701e2()    Unknown
     MSO.DLL!32579fe1()    Unknown
     ACECORE.DLL!33f54973()    Unknown
     ACECORE.DLL!33f55b5b()    Unknown
     ACECORE.DLL!33f70276()    Unknown
     ACECORE.DLL!33ff2494()    Unknown
     ACEOLEDB.DLL!33bc37ac()    Unknown
     [External Code]    
>    S3.exe!S3.Common.OpenSSSDBConnection() Line 919    Basic
     S3.exe!S3.Common.SelectSSSData(String sqlSelect) Line 893    Basic
     S3.exe!S3.Common.GetZiehlFanPartID(String ManufacturerModel) Line 11917    Basic
     S3.exe!S3.FanInfo.GetZiehlFanDimensions() Line 1566    Basic
     S3.exe!S3.FanInfo.dgFans_SelectionChanged(Object sender, System.Windows.Controls.SelectionChangedEventArgs e) Line 1811    Basic
     [External Code]    
     S3.exe!S3.FanInfo.LoadFanTable(String TCFanType) Line 605    Basic
     S3.exe!S3.FanInfo.SelectCurrentFanData(String FanModel, String MotorPosition) Line 1070    Basic
     S3.exe!S3.FanInfo.LoadFanInfo() Line 384    Basic
     S3.exe!S3.FanInfo.ReloadInputData(Object sender, System.Windows.RoutedEventArgs e) Line 1040    Basic
     [External Code]    
     S3.exe!S3.FanInfo.btnZiehl_Click(Object sender, System.Windows.RoutedEventArgs e) Line 1757    Basic
     [External Code]    
     S3.exe!S3.UC.DoOpenComponent(System.Windows.Controls.Image OpenImage) Line 2236    Basic
     S3.exe!S3.UC.ImageOnPanel_MouseLeftButtonDown(Object sender, System.Windows.Input.MouseButtonEventArgs e) Line 1100    Basic
     [External Code]    



Viewing all 18858 articles
Browse latest View live


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