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

How to use data template to render dynamic form UI (label, textbox, button)

$
0
0

I would like to implement render dynamic UI in WPF by using data template. 

This image below shown the UI I would like to achieve:

What I was achieve:


Window XAML

<Window x:Class="TestDataTemplateWithGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:vm="clr-namespace:TestDataTemplateWithGrid"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"><Window.Resources><DataTemplate x:Key="ModelTemplate" DataType="{x:Type vm:DataModel}"><StackPanel Orientation="Horizontal" Width="300"><TextBlock Width="100" Text="{Binding ModelLabel}" HorizontalAlignment="Left" VerticalAlignment="Center" /><TextBox Width="115" Height="25" Text="{Binding ModelValue}" /></StackPanel></DataTemplate><ItemsPanelTemplate x:Key="FormatTemplate"><WrapPanel Orientation="Horizontal"/></ItemsPanelTemplate></Window.Resources><StackPanel><ItemsControl ItemsSource="{Binding MainWindowCollection}" Width="600" ItemTemplate="{StaticResource ModelTemplate}" ItemsPanel="{StaticResource FormatTemplate}" /></StackPanel></Window>

Window C#

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }
    }

Main Window View Model C#

public class MainWindowViewModel : INotifyPropertyChanged
    {
        private DataModel _dataModel = new DataModel();

        public DataModel _DataModel
        {
            get { return _dataModel; }
            set { _dataModel = value; }
        }

        private ObservableCollection<DataModel> mainWindowCollection = new ObservableCollection<DataModel>();

        public ObservableCollection<DataModel> MainWindowCollection
        {
            get { return mainWindowCollection; }
            set { mainWindowCollection = value; }
        }

        private ICommand _sbumitCommand;

        public ICommand _SubmitCommand
        {
            get { return _sbumitCommand; }
            set { _sbumitCommand = value; }
        }

        public MainWindowViewModel()
        {
            mainWindowCollection.Add(new DataModel() { ModelLabel = "A", ModelValue = "1" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "B", ModelValue = "2" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "C", ModelValue = "1" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "D", ModelValue = "1" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "E", ModelValue = "2" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "F", ModelValue = "1" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "G", ModelValue = "2" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "H", ModelValue = "2" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "I", ModelValue = "1" });
            mainWindowCollection.Add(new DataModel() { ModelLabel = "J", ModelValue = "2" });

            _sbumitCommand = new RelayCommand(ExecuteSubmitCommand);
        }

        public void ExecuteSubmitCommand(object param)
        {
           MessageBox.Show("Submit Message !");
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }

Data Model C#
public class DataModel
    {
        private string modelValue;

        public string ModelValue
        {
            get { return modelValue; }
            set { modelValue = value;  }
        }

        private string modelLabel;

        public string ModelLabel
        {
            get { return modelLabel; }
            set { modelLabel = value; }
        }
    }





Web Browser control new Window issue and support for Tabs

$
0
0

Recently working with WPF's web browser and found out that there is know way to know if a new window will open.

If for a link there is a "Target" Attribute like below <a href="<link>"target="blank">Clear Here</a>

Then the browse control will open the link in new browser and not give any event or way to avoid that.

this will also happen if user tries open a new window through javascript

function openWin()   { win = window.open("<link>"); }

This can we achieved with windows form Web Browser control but even that is not full proof as it does not give you any way to know which link will be opened in new windows.

Is there some way to achieve this and also know which link is being opened.


WPF / Powershell - Gridview - change row color

$
0
0

Is there a way to change the row color?

I have tried using data triggers but get errors.

I have tried something very similar to this:


<Style TargetType="DataGridRow"><Style.Triggers><DataTrigger Binding="{Binding Path=City_name}" Value="SomeCity"><Setter Property="Background" Value="{StaticResource SomeCityBackground}"/></DataTrigger></Style.Triggers></Style>
Thanks.



Binding to nested Listbox SelectedItem in Custom Control

$
0
0

I've been searching for a while and haven't been able to find a solution.

My goal is to bind a property in my ViewModel to the selected item of a listbox in my custom control.

First off - This calendar control has been sourced from Jarloo Custom Calendar. I have merely been modifying it for custom personal use. 

The calendar control is as below:

<ResourceDictionary

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ie="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"

    xmlns:Neptune="clr-namespace:Neptune.Calendar"
    xmlns:Converters="clr-namespace:Neptune.Calendar.Converters"><!--xmlns:si="clr-namespace:Expression.Samples.Interactivity;assembly=Expression.Samples.Interactivity"--><Converters:DateConverter x:Key="DateConverter"></Converters:DateConverter><Converters:DayBorderColorConverter x:Key="DayBorderColorConverter"></Converters:DayBorderColorConverter><Style TargetType="{x:Type Neptune:Calendar}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Neptune:Calendar}"><Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"><DockPanel><TextBlock Text="{Binding Date}" /><Grid Height="30" DockPanel.Dock="Top"></Grid><!--Day Names Header--><ItemsControl ItemsSource="{Binding DayNames}" DockPanel.Dock="Top" Foreground="WhiteSmoke"><ItemsControl.ItemTemplate><DataTemplate><TextBlock TextAlignment="Center" Text="{Binding}"><TextBlock.Background><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF171717" Offset="0"/><GradientStop Color="#FF040404" Offset="1"/></LinearGradientBrush></TextBlock.Background></TextBlock></DataTemplate></ItemsControl.ItemTemplate><ItemsControl.ItemsPanel><ItemsPanelTemplate><UniformGrid Rows="1" Columns="7" /></ItemsPanelTemplate></ItemsControl.ItemsPanel></ItemsControl><!--Calendar--><ListBox ItemsSource="{Binding Days}" Background="{x:Null}" SelectedItem="{Binding SelectedDay, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                     x:Name="ListboxDays" ><!--Template--><ListBox.ItemTemplate><DataTemplate><!--Box--><Border BorderBrush="Black" BorderThickness="1" Padding="0"><Border Name="InnerBorder" BorderBrush="{Binding Path=Notes, Converter={StaticResource DayBorderColorConverter}}" BorderThickness="2"><Border.Style><Style TargetType="{x:Type Border}"><Style.Triggers><!--Current Day--><DataTrigger Binding="{Binding IsToday}" Value="true"><Setter Property="Border.Background"><Setter.Value><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF1EA6C8" Offset="0"/><GradientStop Color="#FF0691B3" Offset="1"/></LinearGradientBrush></Setter.Value></Setter></DataTrigger><DataTrigger Binding="{Binding IsFocused, ElementName=TxtBxNotes}" Value="true"><Setter Property="Background" Value="Pink" /></DataTrigger></Style.Triggers></Style></Border.Style><DockPanel><!--Day Number--><StackPanel Orientation="Horizontal" DockPanel.Dock="Top" FlowDirection="RightToLeft"><TextBlock TextAlignment="Right" Text="{Binding Date, Converter={StaticResource DateConverter}, ConverterParameter=DAY}" FontSize="14" Margin="5,5,5,5" ><TextBlock.Style><Style TargetType="{x:Type TextBlock}"><Style.Triggers><DataTrigger Binding="{Binding IsTargetMonth}" Value="false"><Setter Property="TextBlock.Foreground" Value="Gray"></Setter></DataTrigger></Style.Triggers></Style></TextBlock.Style></TextBlock></StackPanel><!--Notes Field--><TextBox IsEnabled="{Binding IsEnabled}" Text="{Binding Notes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                                             AcceptsReturn="True" TextWrapping="Wrap" BorderThickness="0" ScrollViewer.VerticalScrollBarVisibility="Auto"
                                                             Background="{x:Null}" Foreground="White" x:Name="TxtBxNotes" ></TextBox></DockPanel></Border></Border></DataTemplate></ListBox.ItemTemplate><ItemsControl.ItemsPanel><ItemsPanelTemplate><UniformGrid Rows="6" Columns="7" /></ItemsPanelTemplate></ItemsControl.ItemsPanel></ListBox></DockPanel></Border></ControlTemplate></Setter.Value></Setter></Style></ResourceDictionary>

I've tried using TemplateBinding, doesn't work also. 

And the Calendar Class:

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace Neptune.Calendar
{
    public class Calendar : Control
    {
        public ObservableCollection<Day> Days { get; set; }
        public ObservableCollection<string> DayNames { get; set; }

        public static readonly DependencyProperty CurrentDateProperty = DependencyProperty.Register("CurrentDate", typeof(DateTime), typeof(Calendar));

        public event EventHandler<DayChangedEventArgs> DayChanged;

        public DateTime CurrentDate
        {
            get { return (DateTime)GetValue(CurrentDateProperty); }
            set { SetValue(CurrentDateProperty, value); }
        }



        //SelectedDay Property
        public static readonly DependencyProperty SelectedDayProperty =
            DependencyProperty.Register("SelectedDay", typeof(Day),
              typeof(Calendar),
              new PropertyMetadata(null, OnSelectedDayChanged));

        public Day SelectedDay
        {
            get { return (Day)GetValue(SelectedDayProperty); }
            set { SetValue(SelectedDayProperty, value); }
        }

        private static void OnSelectedDayChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
        {
            Calendar d = pager as Calendar;
            //d.SetValue(SelectedDayProperty, e.NewValue);
            //MessageBox.Show(d.SelectedDay.Date.ToShortDateString());///THIS SHOWS CORRECT VALUE
            //d.SetValue(ThisDayProperty, d.SelectedDay);
        }



        public Day ThisDay
        {
            get { return (Day)GetValue(ThisDayProperty); }
            set { SetValue(ThisDayProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ThisDay.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ThisDayProperty =
            DependencyProperty.Register("ThisDay", typeof(Day), typeof(Calendar), new FrameworkPropertyMetadata
            {
                BindsTwoWayByDefault = true,
            });






        static Calendar()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Calendar), new FrameworkPropertyMetadata(typeof(Calendar)));

            //SelectedDayProperty.OverrideMetadata(typeof(Day),
            //                            new FrameworkPropertyMetadata(new Day(),
            //                                FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            //                                new PropertyChangedCallback(Calendar_SelectedDayPropertyChanged)));
        }

        public Calendar()
        {
            DataContext = this;
            CurrentDate = DateTime.Today;

            //this won't work in Australia where they start the week with Monday. So remember to test in other
            //places if you plan on using it.
            DayNames = new ObservableCollection<string> { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

            Days = new ObservableCollection<Day>();
            BuildCalendar(DateTime.Today);
        }

        public void BuildCalendar(DateTime targetDate)
        {
            Days.Clear();

            //Calculate when the first day of the month is and work out an
            //offset so we can fill in any boxes before that.
            DateTime d = new DateTime(targetDate.Year, targetDate.Month, 1);
            int offset = DayOfWeekNumber(d.DayOfWeek);
            if (offset != 1) d = d.AddDays(-offset);

            //Show 6 weeks each with 7 days = 42
            for (int box = 1; box <= 42; box++)
            {
                Day day = new Day { Date = d, Enabled = true, IsTargetMonth = targetDate.Month == d.Month };
                day.PropertyChanged += Day_Changed;
                day.IsToday = d == DateTime.Today;
                Days.Add(day);
                d = d.AddDays(1);
            }
        }

        private void Day_Changed(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName != "Notes") return;
            if (DayChanged == null) return;

            DayChanged(this, new DayChangedEventArgs(sender as Day));
        }

        private static int DayOfWeekNumber(DayOfWeek dow)
        {
            return Convert.ToInt32(dow.ToString("D"));
        }

    }

    public class DayChangedEventArgs : EventArgs
    {
        public Day Day { get; private set; }

        public DayChangedEventArgs(Day day)
        {
            this.Day = day;
        }
    }
}

In the SelectedDayChanged Event, I can see the correct value in the SelectedDay and ThisDay (temp testing DP). But I cannot pass that value up through the the ViewModel.

In the UserControl that utilizes this CustomControl, I have tried binding to this SelectedDay Property and even made another DP (ThisDay) to pass the value to just for testing. Neither values are binding correctly.

<Neptune:Calendar Grid.Row="1" x:Name="Calendar" Margin="0,10,0,0"
   ThisDay="{Binding DaySelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
    RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">

DaySelected is a public property in my viewmodel that implements INotifyPropertyChanged. The RelativeSource Binding was just another solution I tested. I don't need it, but it doesn't hurt either.

I don't understand... Why is this not working? 
All I want to do is expose a property that reflects the selected item in the calendar list of Days.

Also, I want to use this in multiple projects in form of a control library. That is why I'm using ControlTemplate in a ResourceDictionary. I'm pretty sure I could make it work if I just made a custom UserControl out of it, but I'd rather have it this way if I can keep it like this.



How to get __RequestVerificationToken Cookie without browser?

$
0
0

I have a Azure Cloud application using AntiforgeryFilters for preventing from CSRF. Now I have another C# WPF application from which I need to send a POST request to Azure App, but the problem is that every Post request has to be validate by AntiforgeryFilter and I need to know two things:

  1. __RequestVerificationToken
  2. __RequestVerificationToken Cookies

I figured out that I should send first time only simple GET Request and my Cloud App return to WPF App simple View containing __RequestVerificationToken . Now I do not know how can I figure out the problem with the __RequestVerificationToken cookies, because I am not using any browser.

Do I Have here any options how I can get the value of __RequestVerificationToken Cookies?

Thanks for all advice.

Framework Crash occurring while entering the Korean-English Convert key in WPF TextBox

$
0
0

Hello.

Once enter the Korean-English Convert Key in WPF text box, System.Enviroment.FailFast Exception was occurred and Framework crashed.
It occurred just once and error message was logged like below. (just 2 logs)

*** .NET Runtime Error ***

Application: MainFrame.exe
Framework Version: v4.0.30319
Description: The application requested process termination through System.Environment.FailFast(string message).
Message: Unrecoverable system error.
Stack:
   at System.Environment.FailFast(System.String)
   at System.Windows.Documents.TextStore.SetFinalDocumentState(MS.Internal.Documents.UndoManager, System.Collections.Stack, Int32, Int32, Int32, Int32, Int32)
   at System.Windows.Documents.TextStore.HandleCompositionEvents(Int32)
   at System.Windows.Documents.TextStore.GrantLockWorker(LockFlags)
   at System.Windows.Documents.TextStore.RequestLock(LockFlags, Int32 ByRef)
   at MS.Win32.UnsafeNativeMethods+ITfKeystrokeMgr.KeyDown(Int32, Int32, Boolean ByRef)
   at MS.Win32.UnsafeNativeMethods+ITfKeystrokeMgr.KeyDown(Int32, Int32, Boolean ByRef)
   at System.Windows.Input.TextServicesContext.Keystroke(Int32, Int32, KeyOp)
   at System.Windows.Input.TextServicesManager.PostProcessInput(System.Object, System.Windows.Input.ProcessInputEventArgs)
   at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(System.Windows.Input.ProcessInputEventHandler, System.Windows.Input.ProcessInputEventArgs)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs)
   at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr, System.Windows.Input.InputMode, Int32, System.Windows.Input.RawKeyboardActions, Int32, Boolean, Boolean, Int32)
   at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(System.Windows.Interop.MSG ByRef, Boolean ByRef)
   at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(System.Windows.Interop.MSG ByRef, System.Windows.Input.ModifierKeys)
   at System.Windows.Interop.HwndSource.OnPreprocessMessage(System.Object)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
   at System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority, System.Delegate, System.Object)
   at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(System.Windows.Interop.MSG ByRef, Boolean ByRef)
   at System.Windows.Interop.ThreadMessageEventHandler.Invoke(System.Windows.Interop.MSG ByRef, Boolean ByRef)
   at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(System.Windows.Interop.MSG ByRef)
   at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(System.Windows.Interop.MSG ByRef)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Window.ShowHelper(System.Object)
   at System.Windows.Window.ShowDialog()
------------------------------------------------------------------------------------- From here our module's stack
   at MainFrame.ModuleGrids.NewWorklistWindow.ShowDialog()
...


*** Application Error ***

Faulting application name: MainFrame.exe, version: 3.3.0.38, time stamp: 0x57f35616
Faulting module name: PresentationFramework.ni.dll, version: 4.0.30319.34209, time stamp: 0x5348b261
Exception Code: 0x80131623
Fault Offset: 0x0000000000d409b8
Faulting process ID: 0x1578
Faulting application start time: 0x01d2245b19cf8521
Faulting application path: D:\Workstation\MainFrame.exe
Faulting module path: C:\windows\assembly\NativeImages_v4.0.30319_64\Presentatio5ae0f00f#\bbb7fc50a73e54c4c8c15f14994f965b\PresentationFramework.ni.dll
Report ID: f929aba1-90ef-11e6-bb64-e4a4719c7bf5



*** Environment ***
Windows Embedded Standard 7 English
.NET Framework 4.6.1
with Korean IME


I read a post, the Exception Code 0x80131623 means just System.Environment.FailFast Exception.
Can anyone provide me the rootcause and solution to this issue?


Which WPF control (DataGrid, ListView, … etc) is the most suitable to use based on the use case below?

$
0
0

the table should be able to:

  • handle multi-line text
  • handle nested columns (to divide between Shares and Group number in each cell)
  • display small pop-ups as the user hover/click each cell (see last pic)
  • dynamically display/remove checkboxes in its cells
  • Able to support binding of datatable to it like a DataGridView

Background (You may skip this section and proceed to the problem in bold below)

I'm trying to create a prototype for a registration system for shareholders when coming for a company's annual meeting (AGM/EGM). A shareholder can attend the meetings having multiple roles. The shareholder uses the amount of their shares to vote for/against the agenda/resolutions set by the company in the meeting. These information of the shareholder should be displayed in a WPF form(See pictures below).

In this use case scenario, the shareholder, Edmund Gay has 2 roles (shareholder and proxy/representative of another shareholder). He has allocated 80 mil shares and 20 billion shares for voting in AGM and EGM respectively. Another shareholer, Desmond Haggard with 100 billion shares has appointed Edmund Gay as his proxy/representative for the AGM as Desmond is unable to attend. Desmond didn't allocate any of his shares for the EGM.

Edmund is trying to group his and Desmond's shares so Desmond's shares will follow whichever direction (for/against) that he(Edmund) voted for in the AGM.

Which WPF control (DataGrid, ListView, ...) is the best to use based on the design and the expected behaviour of the design below?

The picture below shows the design and how the table should behave based on Edmund's interactions with it.



XAML is not loading, d:Height & d:Width are not recognized?

$
0
0
<UserControl x:Class="PressureVessels.UserControls.NozzleUC"
             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:sys="clr-namespace:System;assembly=mscorlib"
              xmlns:UC="clr-namespace:PressureVessels.UserControls"
             xmlns:vm="clr-namespace:PressureVessels.ViewModel"
             xmlns:l="clr-namespace:PressureVessels"
             xmlns:c="clr-namespace:PressureVessels.Controls"
             mc:Ignorable="d" d:Height="1267" d:Width="698"><UserControl.DataContext><vm:NozzleVM/></UserControl.DataContext>

It used to work, but all of a sudden it has stop working. It doesn't recognize blend. 


Windows media player embbeded in winforms not playing network files continously

$
0
0
Hi,

I just included a windows media player in a winform (using wmplib dll). And this form was called in an WPF window to play network videos(Playing videos from the server, which is a growing video file). I found that it will play only till that time stamp to which it was there when play button was clicked. After that the video file grows, but is not playing that portions in the player. But when it is seeked to the last position for 2-3 times repeatedly the player will play continuously as long as it reaches the end of stream even if it is a growing file. I found it really weird. Any suggestions to help me out... 

Thanks in advance.

Implementing Hit Testing for Strokes of InkCanvas

$
0
0

I've implemented a custom InkCanvas and multiple custom Strokes, which are described here: Custom Rendering Ink

Every thing works fine, except I can't do Hit Testing on my strokes.

At the "Implementing Custom Strokes" section of the above link, it says:

The Stroke class can also perform hit testing. You can also implement your own hit testing algorithm by overriding the HitTest method in the current class.

but i cant find any override-able version of HitTest method there!!!

Can anybody please help me implement hit testing on a custom stroke?

Thanks

Show Active X page in WPF WebBrowser: Cannot create more than one System.Windows.Application instance in the same AppDomain

$
0
0

I want to display a website (which is Active app) in WPF WebBrowser.

Everything is good when target framework is .NET <= 3.5 but the mandatory is .NET >= 4.0 

Then I got exception:

"System.InvalidOperationException: Cannot create more than one System.Windows.Application instance in the same AppDomain.\r\n at System.Windows.Application..ctor()\r\n at WebClientApp.Run_(WebClientApp* , InitializationParams* initParams)\r\n at Eagle.Application.Run(Application* , InitializationParams* )\r\n at WebClientHostControl.AppInitThread_()\r\n at System.Threading.ThreadHelper.ThreadStart_Context(Object state)\r\n at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n at System.Threading.ThreadHelper.ThreadStart()

<WebBrowser x:Name="WebBrowser" Source="http://xxxx:38880/webclient/index.html"/>


how to access a Controltemplate from out resources?

$
0
0

Hey,

i declared a Controltemplate inside a Grid.Resource in Xaml. I need to access it from codebehind. I could find the Template with the findResources syntax. But the VisualTree property stays empty nd without a FrameworkElement, to which the template is applied, i can not use FindName. What to do?? 

Textbox with UpdateSourceTrigger=Explicit and Converter string to object : can't bind properly

$
0
0

Hello,

I have a textbox and I want to bind its Text to a currentMsg object (class Message).

More precisely, when I trigger a TextBox change (in my code, it's explicit and triggered when the user presses enter or clicks on Send), I want the CurrentMsg to be changed with all properties set to default except its body which should be set to the Text in the Textbox.

Here is my code : xaml

<Window x:Class="WpfApplication2.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:WpfApplication2"
        xmlns:vm="clr-namespace:WpfApplication2.ViewModel"
        mc:Ignorable="d"
        DataContext="{Binding Path=Main, Source={StaticResource Locator}}"
        Title="MainWindow" Height="350" Width="525"><Window.Resources><vm:StringToMessageConverter x:Key="ConverterToMessage"/></Window.Resources><Grid Background="White"><Grid.ColumnDefinitions><ColumnDefinition Width="2*"/><ColumnDefinition Width="45*"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="15*"/><RowDefinition Height="304*"/></Grid.RowDefinitions><TextBox x:Name="textBox_msg" KeyUp="TextBox_KeyEnterUpdate" Margin="0,246,100,29" Grid.Row="1" Grid.Column="1" Background="Black" Text="{Binding CurrentMsg, Mode=OneWay, Converter={StaticResource ResourceKey=ConverterToMessage}, UpdateSourceTrigger=Explicit}" Foreground="#FF2F9C34" SelectionBrush="#FF7D3F87" BorderBrush="White"/><ListView x:Name="listBox_chat" Grid.Column="1" ItemsSource="{Binding CurrentMsgList}" DisplayMemberPath="Body" HorizontalAlignment="Left" Height="187" Grid.Row="1" VerticalAlignment="Top" Width="238" Margin="0,42,0,0" Background="#FF91CDD6"/><Button x:Name="button_send" Content="Send" Grid.Column="1" HorizontalAlignment="Left" Height="29" Margin="400,246,0,0" Grid.Row="1" VerticalAlignment="Top" Width="69" Click="button_send_Click"/><ListView x:Name="listBox_clients" ItemsSource="{Binding ConnectedUsers}" DisplayMemberPath="Name" SelectedItem="{Binding CurrentInterlocutor}" Grid.Column="1" HorizontalAlignment="Left" Height="196" Margin="325,42,0,0" Grid.Row="1" VerticalAlignment="Top" Width="160" Background="#FFDDDDDD" BorderBrush="#FF707070"><ListView.ItemContainerStyle><Style TargetType="{x:Type ListViewItem}"><Style.Triggers><DataTrigger Binding="{Binding HasSentANewMessage}" Value="true"><Setter Property="Background" Value="Aqua"/></DataTrigger><DataTrigger Binding="{Binding HasSentANewMessage}" Value="false"><Setter Property="Background" Value="Brown"/></DataTrigger></Style.Triggers></Style></ListView.ItemContainerStyle></ListView><Label x:Name="label_welcome" Content="{Binding WelcomeMsg}" Grid.Column="1" HorizontalAlignment="Left" Height="37" Grid.Row="1" VerticalAlignment="Top" Width="176"/></Grid></Window>

xaml.cs

using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using WpfApplication2.ViewModel;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TextBox_KeyEnterUpdate(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Console.WriteLine("enter");
                UpdateTextBoxBinding(sender as TextBox);
                KeepScrollDown();
            }
        }

        private void button_send_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("click");
            UpdateTextBoxBinding(textBox_msg);
            KeepScrollDown();
            /*var dialog = new CommonOpenFileDialog();
            dialog.IsFolderPicker = false;
            CommonFileDialogResult result = dialog.ShowDialog();*/
            //if (result)) { Console.WriteLine(dialog.FileName); }
        }


        private void UpdateTextBoxBinding(TextBox tBox)
        {
            DependencyProperty prop = TextBox.TextProperty;
            BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop);
            if (binding != null) { binding.UpdateSource(); Console.WriteLine("binding updated"); }

        }

        private void KeepScrollDown ()
        {
            if (VisualTreeHelper.GetChildrenCount(listBox_chat) > 0)
            {
                Border border = (Border)VisualTreeHelper.GetChild(listBox_chat, 0);
                ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
                scrollViewer.ScrollToBottom();
            }
        }

    }
}


MainViewModel.cs

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace WpfApplication2.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        public string Name { get; private set; }
        public string WelcomeMsg { get; private set; }


        private Message currentMsg { get; set; } = new Message();
        public Message CurrentMsg
        {
            get { return currentMsg; }
            set
            {
                currentMsg = value;
                Console.WriteLine("changed current Msg ?");
            }
        }


        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ////if (IsInDesignMode)
            ////{
            ////    // Code runs in Blend --> create design time data.
            ////}
            ////else
            ////{
            ////    // Code runs "for real"
            ////}



            Name = "John";
            WelcomeMsg = $"Bienvenue sur PtiChat, {Name}";


        }





    }
}

Message.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication2
{
    public class Message
    {
        public string Body { get; set; }
        public string Sender { get; set; }
    }
}

StringToMessageConverter.cs

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace WpfApplication2.ViewModel
{
    public class StringToMessageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Console.WriteLine("Converter ?");
            //throw new NotImplementedException();
            String str = value as string;
            if (str == null)
            {
                Console.WriteLine("Converter ? Null");
                return null;
            } else
            {
                Console.WriteLine("Converter ? Not Null");
                return new Message { Body = str };
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Console.WriteLine("convertBack");
            throw new NotImplementedException();
        }
    }
}

Je m'excuse par avance de la longueur du poste. 

Merci pour votre réponse.

Custom WPF-validation rules crash designer

$
0
0

Hi,

we're encountering a strange issue with custom validation rules. When designing a WPF-UserControl everything is fine until with add custom made validation rules to any binding. Once we did that, the designer instantly crashes with a NullReferenceException. The displayed callstack ends in BindingExpressionBase.Validate.

We played around to narrow the problem down, but everything we learned is:

- Using build-in validation rules works
- The exception is not caused within the custom validation rule. We created a blank rule without any logic, always returning "Valid" and the problem occurs
- The exception occurs wether the rule is defined in the same or a different project.
- Commenting the validation rules out instantly restores the designer
- The validation rules do work as expected at runtime

Sample XAML-code:

<ComboBox
  DisplayMemberPath="Name"
  Margin="120 0 0 0"
  Name="SomeComboBox"><ComboBox.SelectedItem><Binding
      Mode="OneWayToSource"
      Path="SomePath"><Binding.ValidationRules><validationRules:NotNullValidationRule
         ValidationStep="RawProposedValue"
         /></Binding.ValidationRules></Binding></ComboBox.SelectedItem></ComboBox>

Exception details:

System.NullReferenceException
Object reference not set to an instance of an object.
   at System.Windows.Data.BindingExpressionBase.Validate(Object value, ValidationStep validationStep)
   at System.Windows.Data.BindingExpression.Validate(Object value, ValidationStep validationStep)
   at System.Windows.Data.BindingExpressionBase.UpdateValue()
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.RunApplication()
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.<>c__DisplayClass5_0.<Main>b__0()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Any ideas?

Display Scaling Issue after Anniversary Update

$
0
0

I've run into an issue with the behavior of my WPF applications (all of them) since the Anniversary Update.  I'm wondering if anyone else has encountered this and what (if anything) you did to fix it.

Problem:

Any control that is based on a list box (or perhaps an items control) behaves strangely if the monitor's display scale is set to anything other than 100%.  Menus will disappear as soon as you click them.  Menu items/list box items are not highlighted when you mouse over them - or the incorrect ones are highlighted.  Clicking them does not select them and so on.  Using the keyboard to select them DOES work.

Drag the application to a monitor where the display scale is set to 100% and it works fine.  Drag it back, it misbehaves again.  It appears as though the application is not properly detecting the mouse position.

I know that the Anniversary Update included display scale changes for WPF.  However, I thought they were largely automatic.  It would seem that's not entirely true.  Any insights would be greatly appreciated.


Custom DrawingBrush for Weather Fronts

$
0
0

Hello. I'm trying to use custom drawing brushes to be able to draw weather fronts (cold, warm, etc.). I've been able to, with much trial and error, get essentially what I want with a straight horizontal line for a warm front (red line with repeating half cicles). However, I don't know how to transform that in a way that it would work with vertical lines, paths, curves, etc. 

Here's what I have so far...

<Line Height="235" Canvas.Left="834" Canvas.Top="294" Width="514" X1="0" Y1="150" X2="514" Y2="150" StrokeThickness="35" ClipToBounds="False"><Line.Stroke><DrawingBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0,0,100,80"><DrawingBrush.Drawing><DrawingGroup><GeometryDrawing Brush="blue"><GeometryDrawing.Geometry><GeometryGroup><LineGeometry  StartPoint="0 -18.5" EndPoint="100 -18.5"  /></GeometryGroup></GeometryDrawing.Geometry><GeometryDrawing.Pen><Pen Thickness="2"><Pen.Brush><SolidColorBrush Color="red" /></Pen.Brush></Pen></GeometryDrawing.Pen></GeometryDrawing><GeometryDrawing Brush="red"><GeometryDrawing.Geometry><!--<EllipseGeometry RadiusX="25" RadiusY="5" Center="35,10" />--><PathGeometry Figures="M 0 -10 Q 37.5 -15 75 -10" /></GeometryDrawing.Geometry></GeometryDrawing></DrawingGroup></DrawingBrush.Drawing></DrawingBrush></Line.Stroke></Line>

Which renders this: 

But if I take that code and put in a path with a curve in it, the path renders like this:

I can understand why it does this, but I need to know how, or at least some clues, to transform the code so it looks properly regardless of the direction/shape of the line.

I should also note that while I am currently doing this in Xaml, I will eventually be doing this in code behind, but I can translate.

Thanks in advance,

Andrew

Image in usercontrol does not update

$
0
0

Dear Community,

after I learnt quite a bit from my last thread, I ran into the next problem. The binding and updating inside my user control work but sadly only for a label and not for an image. I found a similar problem in a thread on the msdn (Title: user control, Image and ImageSource) but I could not adapt the solution. My guess would be that I got somehow confused by the whole bitmap/imagesource/imagestream-thing and use the wrong dependency property configuration.

To give a small overview: In my programm I bind a string property to a label in the usercontrol and a writeablebitmap to an image. In both cases I set up a dependecy property and the label changes when the string changes. The remaining problem is that my writeablebitmap does not show up in the usercontrol.

My whole problem solving goes around in circles, so I hope you can give me some fresh input.

Thank you very much in advance and best regards,

Apfelman

Below you can see the code for my usercontrol:

ViewImageData.xml

<UserControl x:Class="CollectionMVVMExample.View.ViewImageData"
             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:CollectionMVVMExample.View"
             xmlns:vm="clr-namespace:CollectionMVVMExample.ViewModel"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="520"
             Name="ImageDataControl"><Grid><StackPanel Margin="4"><Label x:Name="lbl_Image" FontSize="14" Content="{Binding Path=DisplayLabel, ElementName=ImageDataControl}"/><Image x:Name="img_Image" Height="424" Source="{Binding Path=BMPSource, ElementName=ImageDataControl}"/></StackPanel></Grid></UserControl>

ViewImageData.xaml.cs

using CollectionMVVMExample.ViewModel;
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;


namespace CollectionMVVMExample.View
{
    /// <summary>
    /// Interaktionslogik für ViewImageData.xaml
    /// </summary>
    public partial class ViewImageData : UserControl
    {

        #region DependencyProperty
        public String DisplayLabel
        {
            get { return (String)GetValue(DisplayLabelProperty); }
            set { SetValue(DisplayLabelProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Source.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DisplayLabelProperty =
            DependencyProperty.Register("DisplayLabel", typeof(String), typeof(ViewImageData), null);



        public WriteableBitmap BMPSource
        {
            get { return (WriteableBitmap)GetValue(BMPSourceProperty); }
            set { SetValue(BMPSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Source.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BMPSourceProperty =
            DependencyProperty.Register("BMPSource", typeof(WriteableBitmap), typeof(ViewImageData), null);
        #endregion

        #region Constructor
        public ViewImageData()
        {
            InitializeComponent();

        }
        #endregion

    }
}

Snippet out of my MainWindow.xaml

<view:ViewImageData x:Name="uc_IR_ViewModel" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center"
                            BMPSource="{Binding IR_ViewModel.DisplayImage}"
                            Content="{Binding IR_ViewModel.ImageLabel}"
                            />

Rendered Rectangles missing in a huge WPF Control

$
0
0

Guys

I need a WPF Control with 300000000 width and height, on which I will draw rectangles, based on some input. I am drawing the rectangle on the OnRender of the control. For testing purpose I have put the control inside a scrollViewer and am drawing rectangles on each pixels from (0,0) to (1000,1000).  If the width & height is 1000000, the rectangles are drawn properly, shown below, (the rectangles are plotted on all the pixels from (0,0) to (1000,1000), so it looks like below)

The code can be entire downloaded from 

Download code here


But If I increase the size to 3000000, few lines are missing in the drawing like below,


My xaml:

<ScrollViewer x:Name="MainScrollViewer"
                      Grid.Row="2"
                      Grid.ColumnSpan="2"
                      HorizontalScrollBarVisibility="Auto"
                      VerticalScrollBarVisibility="Auto"><waferControl:WaferMapControl x:Name="WaferControl"
                                          Grid.Row="2"
                                          Grid.ColumnSpan="2"
                                          Width="30000000"
                                          Height="30000000"
                                          Margin="10"
                                          ColumnCount="{Binding WaferInfo.ColumnCount}"
                                          RowCount="{Binding WaferInfo.RowCount}"
                                          SelectedCells="{Binding SelectedCellCollection}"
                                          Visibility="Collapsed" /></ScrollView

I am using the following code in OnRender of WaferMapControl,

        private void RenderBackgroud(IEnumerable lists)
        {
            using (DrawingContext dc = _backgroundDv.RenderOpen())
            {
                SolidColorBrush brush = Brushes.Black;
                if (brush.CanFreeze) brush.Freeze();
                foreach (GridCellInfo cellInfo in lists)
                {
                    double length = cellInfo.GridRange;
                    var point = new Point(cellInfo.RowIndex + 1, ActualHeight - cellInfo.ColumnIndex  - length);
                    RenderBackgroud(dc, point, brush, length);
                }
            }
        }

private void RenderBackgroud(DrawingContext dc, Point point, Brush brush, double length) { var rect = new Rect(point, new Size(length, length)); dc.DrawRectangle(brush, null, rect); }
Can someone help me out, what is the issue here. Let me know if you require anything from my side.





I'm stuck with getting a value back from another click event

$
0
0

I've started to build an Memory Card game, but I got stuck with retrving a value from the second clicked button, but first I'll write what I planed the game to be like:

After you click a button, an Image will apper at the same place of the button for 5 seconds, at those 5 seconds you have to click another button, if you don't the click event will end, if you pick a matching picture - they both stay open forever, but if you open another picture they both will appear for extra 3 seconds.

I already tried to solve that, I'm not just running to here, I'm sitting 2 days exploring options to do that.

What have I done so far: I've made a dictonary which "Button" is the key and "String" is the name of the picture, what I've planned to do is: When 2 pictures are clicked - the first click would get the Button's name and return a string value which will be compared to the string value of that button, and if they match, they both stay open.

Because I can't post a screenshot untill msdn will verify my account, that's the xaml code:

<Page
    x:Class="MemoryGame.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MemoryGame"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"><Page.Resources><Style TargetType="Image" x:Key="HideableImages"><Setter Property="Visibility" Value="Collapsed" /><Setter Property="HorizontalAlignment" Value="Stretch" /><Setter Property="VerticalAlignment" Value="Stretch" /><Setter Property="Stretch" Value="Fill" /></Style><Style x:Key="QuesionMarkButton" TargetType="Button"><Setter Property="HorizontalAlignment" Value="Stretch"/><Setter Property="VerticalAlignment" Value="Stretch"/><Setter Property="BorderBrush" Value="Black"/><Setter Property="FontFamily" Value="Segoe MDL2 Assets"/><Setter Property="Content" Value="&#xE897;"/><Setter Property="FontSize" Value="72"/></Style></Page.Resources><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"><Grid.ColumnDefinitions><ColumnDefinition Width="1*"/><ColumnDefinition Width="1*"/><ColumnDefinition Width="1*"/><ColumnDefinition Width="1*"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="1*"/><RowDefinition Height="2*"/><RowDefinition Height="2*"/><RowDefinition Height="2*"/><RowDefinition Height="2*"/></Grid.RowDefinitions><TextBlock Name="Title" FontSize="36" Text="Memory game by Ido levi" Grid.ColumnSpan="4"/><Button Name="R1C1" BorderThickness ="0,0,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="1" Grid.Column="0" Click="R1C1_Click"    PointerPressed="R1C1pressed" /><Button Name="R1C2" BorderThickness="3,0,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="1" Grid.Column="1" Click="R1C2_Click_1" PointerPressed="R1C2_PointerPressed"/><Button Name="R1C3" BorderThickness="3,0,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="1" Grid.Column="2"  /><Button Name="R1C4" BorderThickness="3,0,0,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="1" Grid.Column="3" /><Button Name="R2C1" BorderThickness="0,3,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="2" Grid.Column="0" /><Button Name="R2C2" BorderThickness="3,3,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="2" Grid.Column="1" /><Button Name="R2C3" BorderThickness="3,3,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="2" Grid.Column="2" /><Button Name="R2C4" BorderThickness="3,3,0,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="2" Grid.Column="3" /><Button Name="R3C1" BorderThickness="0,3,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="3" Grid.Column="0" /><Button Name="R3C2" BorderThickness="3,3,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="3" Grid.Column="1" /><Button Name="R3C3" BorderThickness="3,3,3,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="3" Grid.Column="2" /><Button Name="R3C4" BorderThickness="3,3,0,3" Style="{StaticResource QuesionMarkButton}" Grid.Row="3" Grid.Column="3" /><Button Name="R4C1" BorderThickness="0,3,3,0" Style="{StaticResource QuesionMarkButton}" Grid.Row="4" Grid.Column="0" /><Button Name="R4C2" BorderThickness="3,3,3,0" Style="{StaticResource QuesionMarkButton}" Grid.Row="4" Grid.Column="1" /><Button Name="R4C3" BorderThickness="3,3,3,0" Style="{StaticResource QuesionMarkButton}" Grid.Row="4" Grid.Column="2" /><Button Name="R4C4" BorderThickness="3,3,0,0" Style="{StaticResource QuesionMarkButton}" Grid.Row="4" Grid.Column="3" /><Image Name="R1C1img"  Grid.Row="1" Grid.Column="0" Style="{StaticResource HideableImages}" Source="Assets/OriginalPepe.jpg"/><Image Name="R1C2img"  Grid.Row="1" Grid.Column="1" Style="{StaticResource HideableImages}" Source="Assets/PixelPepe.jpg"/><Image Name="R1C3img"  Grid.Row="1" Grid.Column="2" Style="{StaticResource HideableImages}" Source="Assets/IronManPepe.jpg"/><Image Name="R1C4img"  Grid.Row="1" Grid.Column="3" Style="{StaticResource HideableImages}" Source="Assets/CoolPepe.jpg"/><Image Name="R2C1img"  Grid.Row="2" Grid.Column="0" Style="{StaticResource HideableImages}" Source="Assets/UrselfPepe.png"/><Image Name="R2C2img"  Grid.Row="2" Grid.Column="1" Style="{StaticResource HideableImages}" Source="Assets/WinkPepe.jpg"/><Image Name="R2C3img"  Grid.Row="2" Grid.Column="2" Style="{StaticResource HideableImages}" Source="Assets/OriginalPepe.jpg"/><Image Name="R2C4img"  Grid.Row="2" Grid.Column="3" Style="{StaticResource HideableImages}" Source="Assets/HappyPepe.jpg"/><Image Name="R3C1img"  Grid.Row="3" Grid.Column="0" Style="{StaticResource HideableImages}" Source="Assets/PixelPepe.jpg"/><Image Name="R3C2img"  Grid.Row="3" Grid.Column="1" Style="{StaticResource HideableImages}" Source="Assets/MonsterPepe.jpg"/><Image Name="R3C3img"  Grid.Row="3" Grid.Column="2" Style="{StaticResource HideableImages}" Source="Assets/CoolPepe.jpg"/><Image Name="R3C4img"  Grid.Row="3" Grid.Column="3" Style="{StaticResource HideableImages}" Source="Assets/IronManPepe.jpg"/><Image Name="R4C1img"  Grid.Row="4" Grid.Column="0" Style="{StaticResource HideableImages}" Source="Assets/WinkPepe.jpg"/><Image Name="R4C2img"  Grid.Row="4" Grid.Column="1" Style="{StaticResource HideableImages}" Source="Assets/UrselfPepe.png"/><Image Name="R4C3img"  Grid.Row="4" Grid.Column="2" Style="{StaticResource HideableImages}" Source="Assets/MonsterPepe.jpg"/><Image Name="R4C4img"  Grid.Row="4" Grid.Column="3" Style="{StaticResource HideableImages}" Source="Assets/HappyPepe.jpg"/></Grid></Page>

That's a 4x4 buttons, what I'm trying to do now is:

After pressing 1 button, that button would be active for 5 seconds and whithin those 5 seconds, he have to catch another clicked button and if not, disable the event.

So my questions is:

- How can I catch a button clicked event?

- How to set the timer for 5 seconds and whithin those 5 seconds, I would be able to click another button (I tried using async await by: await System.Threading.Tasks.Task.Delay(5000);, it does stop for 5 seconds but at those 5 seconds I couldnt press another buttons


property value changing back to null inside combobox of a datagrid column mvvm wpf project

$
0
0

Hi

I have a datagrid with two columns . First column has a combo box to choose a value from  and second column is a text box . Both of them display data correctly . This datagrid data collection is part of a model which is bound to tree view called myOrgTree.

DataGrid inside TreeView:

<DataGrid x:Name="myPropCollection" CanUserDeleteRows="True" Width="900"
                                  CanUserAddRows="False" CanUserResizeColumns="True" CanUserResizeRows="False"
                                   ItemsSource="{Binding ElementName=myOrgTree, Path=SelectedItem.OrgPropCollection,
                                                Mode=TwoWay}"
                                  SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor,
                                  AncestorType={x:Type UserControl}}, Path=DataContext.SelectedproductNameValue}"
                                  AutoGenerateColumns="False"
                                  EnableRowVirtualization ="False"  Margin="0,2,0.333,-2.333"><DataGrid.RowHeaderStyle><Style TargetType="DataGridRowHeader"><Setter product="Width"><Setter.Value>20</Setter.Value></Setter><Setter product="Content"><Setter.Value><MultiBinding Converter="{StaticResource rowToIndexConverter}"><Binding /><Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}" /></MultiBinding></Setter.Value></Setter></Style></DataGrid.RowHeaderStyle><DataGrid.Columns><!--product name coclumn--><DataGridTemplateColumn Header="product" Width="*"><DataGridTemplateColumn.CellEditingTemplate><DataTemplate><ComboBox
                                                     ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
                                                     AncestorType={x:Type UserControl}}, Path=DataContext.productNameCollection}"
                                                     Width="200"  x:Name="xProperties"
                                                     SelectedItem ="{Binding RelativeSource={RelativeSource FindAncestor,
                                                     AncestorType={x:Type Grid}}, Path=DataContext.productName}"
                                                     SelectedValue="{Binding productName}"><ComboBox.ItemTemplate><DataTemplate><TextBlock  Text="{Binding}" /></DataTemplate></ComboBox.ItemTemplate></ComboBox></DataTemplate></DataGridTemplateColumn.CellEditingTemplate><DataGridTemplateColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding productName,Mode=TwoWay}"  ></TextBlock></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn><!--value name coclumn--><DataGridTextColumn Header="Value" Width="*" Binding="{Binding productValue,Mode=TwoWay}" /></DataGrid.Columns></DataGrid>

my model which is bound to datagrid.OrgPRopCollection is an observable collection of  PRoductNameValueModel.                                   

    public class ProductNameValueModel: NodeBase
    {
        private string _ProductName;
        public string ProductName
        {
            get { return _ProductName; }

            set
            {
                if (value != null)
                {
                    _ProductName = value;
                    NotifyProductChanged("ProductName");
                }roperty

            }
        }


        private string _ProductValue;
        public string ProductValue
        {
            get { return _ProductValue; }

            set
            {
                _ProductValue = value;
                NotifyProductChanged("ProductValue");
            }
        }

    }//cls
while my datagrid displays data correctly , when i switch to another treeview item , the values in the previous/current treeViewitem's ProductName column are set to null which erases the values selected by user.  Whereas PRoductValue column (which is simply a textbox) could retain its value.To avoid this i have put a condition which is to check whether the ProductName value is not null. Since its just a workaround i would like to know how we can fix it in the first place. 


Krrishna



Viewing all 18858 articles
Browse latest View live


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