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

To stretch my view over my region

$
0
0

Hello!

I have a view that is loaded to a region as the result of an event. 

The problem is that it occupies only a certain part of the region area. I do want it to spread over the whole area of my region.

How to achieve it?

Thank you!


Wpf toolkit chart control throws error cannot modify the logical children for this node at this time because a tree walk is in progress

$
0
0

<UserControl x:Class="Rad_AccuracyReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="500" d:DesignWidth="1200" Loaded="UserControl_Loaded" >
    <Grid>
        <DatePicker Height="25" HorizontalAlignment="Left" Margin="240,67,0,0" Name="DatePickerFromDate" VerticalAlignment="Top" Width="154" />
        <DatePicker Height="25" HorizontalAlignment="Left" Margin="488,67,0,0" Name="DatePickerToDate" VerticalAlignment="Top" Width="155" />
        <Label Content="From Date :" Height="28"  Foreground="White"     HorizontalAlignment="Left" Margin="155,67,0,0" Name="lblFromDate" VerticalAlignment="Top" Width="79" />
        <Label Content="To Date :" Height="28" Foreground="White"        HorizontalAlignment="Left"  Margin="420,67,718,0" Name="lblToDate" VerticalAlignment="Top" Width="68" />
        <Button Content="Submit" Height="23" HorizontalAlignment="Left" Margin="240,105,0,0" Name="Button1" VerticalAlignment="Top" Width="96" />
        <Grid Height="921" Margin="-25,0,25,0">
            <chartingToolkit:Chart Height="262" HorizontalAlignment="Left" 
            Margin="33,0,0,620" Name="ColumnChart1" Title="Department"
            VerticalAlignment="Bottom" Width="410">
                <chartingToolkit:ColumnSeries DependentValuePath="Value"  IndependentValuePath="Key" ItemsSource="{Binding}"
            IsSelectionEnabled="True"></chartingToolkit:ColumnSeries>
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="AreaChart1" Title="Department" Margin="828,39,0,629" HorizontalAlignment="Left" Width="378">
                <chartingToolkit:AreaSeries DependentValuePath="Value"
          IndependentValuePath="Key" ItemsSource="{Binding}"
            IsSelectionEnabled="True"/>
            </chartingToolkit:Chart>
            <!--<chartingToolkit:Chart  Name="BarChart1" Title="Department" Margin="547,307,19,358" Width="450">
                <chartingToolkit:BarSeries  DependentValuePath="Value"
            IndependentValuePath="Key" ItemsSource="{Binding}"
            IsSelectionEnabled="True"/>
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="PieChart1" Title="Department" Width="380"
            VerticalAlignment="Top" Margin="428,39,0,0" Height="262" HorizontalAlignment="Left">
                <chartingToolkit:PieSeries DependentValuePath="Value"
            IndependentValuePath="Key" ItemsSource="{Binding}"
            IsSelectionEnabled="True" />
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="LineChart1" Title="Department" Width="450" Margin="33,309,533,358">
                <chartingToolkit:LineSeries  DependentValuePath="Value"
            IndependentValuePath="Key" ItemsSource="{Binding}"
            IsSelectionEnabled="True"/>
            </chartingToolkit:Chart>
            <chartingToolkit:Chart Name="BubbleSeries1" Title="Department" Width="420" Height="300" Margin="573,570,302,51">
                <chartingToolkit:BubbleSeries IndependentValuePath="Key" DependentValuePath="Value" IsSelectionEnabled="True" ItemsSource="{Binding}"></chartingToolkit:BubbleSeries>
            </chartingToolkit:Chart>
            <chartingToolkit:Chart Name="ScatterSeries1" Title="Department" Width="420" Height="300" Margin="138,570,737,51">
                <chartingToolkit:ScatterSeries IndependentValuePath="Key" DependentValuePath="Value" IsSelectionEnabled="True" ItemsSource="{Binding}"></chartingToolkit:ScatterSeries>
            </chartingToolkit:Chart>-->

        </Grid>
        <Grid >

          <DataGrid  IsReadOnly="True"    HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"  Height=" 200" AutoGenerateColumns="True" HorizontalAlignment="Left" Margin="64,199,0,0" Name="DGV_Accuracy" VerticalAlignment="Top" Width= "791" Visibility="Hidden"  />
            <Label Content="Accuracy Report :" Height="28" HorizontalAlignment="Left" Margin="64,6,0,0" Name="lblHeader" VerticalAlignment="Top" Width="134" Foreground="White"        />
        </Grid>
    </Grid>
</UserControl>

Private Sub LoadDataGrid()
        Try
            If dbCon.State = ConnectionState.Closed Then dbCon.Open()
            'strSql = "Rad_GetDailyAccuracy  '" & DatePickerFromDate.SelectedDate & "', '" & DatePickerToDate.SelectedDate & "'"
            strSql = "Rad_GetDailyAccuracy_temp  '" & DatePickerFromDate.SelectedDate & "', '" & DatePickerToDate.SelectedDate & "'"
            dbCom = New SqlCommand
            dbCom.Connection = dbCon
            dbCom.CommandText = strSql
            dbAdap.SelectCommand = dbCom
            dsRecord = New DataSet
            dbAdap.Fill(dsRecord)
            dbAdap.Dispose()
            If dsRecord.Tables(0).Rows.Count > 0 Then
                DGV_Accuracy.ItemsSource = dsRecord.Tables(0).DefaultView
                DGV_Accuracy.Visibility = Windows.Visibility.Visible
                DGV_Accuracy.Columns(0).Visibility = Windows.Visibility.Hidden
                DGV_Accuracy.Columns(1).Width = 120

                DGV_Accuracy.Columns(2).Width = 250
                DGV_Accuracy.Columns(3).Width = 120
                DGV_Accuracy.Columns(DGV_Accuracy.Columns.Count - 1).Width = New DataGridLength(1, DataGridLengthUnitType.Star)
                Dim MyValue As New List(Of KeyValuePair(Of String, Integer))()

                For Each dr As DataRow In dsRecord.Tables(0).Rows
                    MyValue.Add(New KeyValuePair(Of String, Integer)(dr("Modality"), dr("Total")))
                Next



                '  ColumnChart1.DataContext = MyValue
                AreaChart1.DataContext = MyValue


            Else
                DGV_Accuracy.Visibility = Windows.Visibility.Hidden
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, AppMsg)
            Exit Sub
        End Try
    End Sub

        

mscorlib recursive resource lookup bug

$
0
0

Hi,

during development our windows-application (.NET) we suddenly got the problem:
"mscorlib recursive resource lookup bug"
during startup the application.(100% reproducable)

The "App.OnStartup(StartupEventArgs e)" is not called anymore, the problem happens before.

Because we could not find the problem and there was no way of receiving any useful error information (also the callstack isn't of any use), I have to post this issue to you, if you know any hint to solve such a problem.

In the meantime we encontered a workaround (100% reproducable) which is just a piece of code without any use - but it SOLVES our problem (100% reproducable):
- throw an exception and handle it => no error anymore
- no exception throwing => error as described
- a thread.Sleep instead of exception-throwing does not help

     public partial class App
    {
        private static MyClass _myclass = new MyClass();
        ....


     public class MyClass
    {
        public MyClass()
        {
            try
            {
                throw new NotImplementedException(); //<<<<< THIS IS THE FIX                
            }
            catch (Exception ex)
            {

            }
        }
    }

Environment:

VS2013 Update 1, Win7 64bit, .NET 4.5 WPF application, DevExpress 13.2.7

The showing error box

Biding MenuItem Commands to Specific Pages

$
0
0

Hello,

I am working in a WPF application that contains a Frame with serveral Pages in it. The Frame object is in a Windows where there is also a Menu with several MenuItems.

I would like to know what would be a good way to respond to MenuItem clicks inside a specific page, since they do not hold a reference to the menu object.

I was thinking about using Command Binding, but not sure how this could be done..

Any toughts?

Igor.


.NET Software developer for industrial internet and automation system.

RemoveVisualChild slow besides low visual count

$
0
0

Hi,

I started playing around with WPF and built a version of Game Of Life as a little exercise where I stumbled over a performance problem I don't really understand.

This is the method which draws the Game of Life board

        public void RefreshBoard()
        {
            _visuals.ForEach(delegate(Visual v) { RemoveVisualChild(v); });
            _visuals.Clear();

            DrawingVisual background = new DrawingVisual();
            using (DrawingContext dc = background.RenderOpen())
            {
                SolidColorBrush brush = (SolidColorBrush)(new BrushConverter().ConvertFrom(_preferences.BackgroundColorHex));
                dc.DrawRectangle(brush, new Pen(brush, 10),
                    new Rect(new Size(_width * (_blockSize + 4), _height * (_blockSize + 4))));
            }
            _visuals.Add(background);

            DrawingVisual board = new DrawingVisual();
            using (DrawingContext dc = board.RenderOpen())
            {
                for (int i = 0; i < _board.GetLength(0); i++)
                {
                    for (int j = 0; j < _board.GetLength(1); j++)
                    {
                        if (_board[i, j] == 0)
                            dc.DrawRectangle(Brushes.Black,
                                new Pen(Brushes.Black, 2),
                                new Rect(new Point(i * (_blockSize + 4), j * (_blockSize + 4)),
                                    new Size(_blockSize, _blockSize)));
                        else
                            dc.DrawRectangle(Brushes.White,
                                new Pen(Brushes.White, 2),
                                new Rect(new Point(i * (_blockSize + 4), j * (_blockSize + 4)),
                                    new Size(_blockSize, _blockSize)));
                    }
                }
            }
            _visuals.Add(board);

            DrawingVisual loggingText = new DrawingVisual();
            using (DrawingContext dc = loggingText.RenderOpen())
            {
                FormattedText t = new FormattedText(logText, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, _BoardTypeface, 12, Brushes.Black);
                dc.DrawText(t, new Point(300, -25));
            }

            _visuals.Add(loggingText);
            _visuals.ForEach(delegate(Visual v) { AddVisualChild(v); });
        }


And everything is smooth as long as the field count doesn't exceed 50x50. I tried 100x100 and that's where things are starting to get slow.

So I tried to figure out where in RefreshBoard() the time get's lost. Of course the double loop takes some time, but that's no surprise, but what really was is the fact that the execution of these two lines

_visuals.ForEach(delegate(Visual v) { RemoveVisualChild(v); });_visuals.Clear();

take almost as long as the double loop. And now I'm wondering, why? The visual count is always exactly 3, the board, the fields and a text.

So why the hell does it take so incredibly long (250ms on my machine to be precise) to remove just 3 visuals?

Cheers

Simon

List items based by user Identity

$
0
0

Hi guys,

I'm creating an application that consists of a Calendar event, which was provided by this website. Furthermore, the application uses custom authentication, allowing each user to have their own credentials and further allowing them to update their own credentials; which was achieved by this previous question asked.

I'm in the middle of tweaking this calendar so it meets my own needs, however; I've come unstuck and therefore would appreciate some guidance. 


The image above shows that you have to enter in a user Id; at the moment this is fine.

However due to my application consisting of several users, they would want to be able to display their events that they have added eg; If user Greg (Id = 1) has entered in an event while user Bob (Id = 2), both appear on the same calendar event. 

Currently, I use the following method to get a list of events, like so;

public List<Event> EventList()
        {
            using (SchoolAdminDBEntities db = new SchoolAdminDBEntities())
            {
                try
                {
                    return db.Appointments.Select(appointement
                        => new Event
                        {
                            Id = appointement.AppointmentID,
                            UserID = appointement.UserID,
                            Subject = appointement.Subject,
                            Location = appointement.Location,
                            Description = appointement.Notes,
                            Start = appointement.StartDate,
                            End = appointement.EndDate
                        }).ToList();
                }
                catch
                {
                    return null;
                }
            }
        }
private ObservableCollection<Event> _events;
        public ObservableCollection<Event> WpfScheduleEvents
        {
            get
            {
                if (_events == null)
                    _events = new ObservableCollection<Event>(rep.EventList();

                return _events;
            }
            set
            {
                if (_events != value)
                {
                    _events = value;
                    OnPropertyChanged("WpfScheduleEvents");
                }
            }
        }


However my question is: Is there a way to display only what an individual user has entered? Is it possible to use "Thread.CurrentPrincipal.Identity.Name;" within this scenario? And if so, how could it be done?

Kind regards,

Greg.




Displaying spatial data on an image and not a map

$
0
0

Hi everyone ,

I am working on drawing spatial data on a image. In found on the net a lot of things to display data but on a map (Bing for instance) and I would like to know if it exists solutions to display data on a simply image ? I searched a lot of time but I did not find a tutorial or something similar. Do you have some ideas about how I could do that ?

Regards,

Mijo 

TabItem Header Visibility

$
0
0

Hi Folks,

I'm displaying two different data object in a TreeView control. When the user selects either of the data object types, I wanted its relvant data details displayed in one of two TabItems in a TabControl, while the other one disappears setting its Visibility property set to Hidden (or Collapsed - I've tried both). I've bound each TabItem's Visibility property to an 'IsSelected' property in its underlying VM and used a converter to change the 'IsSelected' bool value to a corresponding Visibility value.

My problem is this; although the content of unselected TabItem dissappears, the actual TabItem, and its Header, are still visible. I thought the setting a TabItem's Visibility property to either Hidden or Collapsed would make it dissappear but this seems not to be the case. I can't find anything definitive in the documentation. Does anyone know what is happening here?

Best regards,

RobDev


RobDev


Datacontext not getting set when applied through datatemplate in resource dictionary.

$
0
0

Hi,

I have done the following steps:

1. Created a ViewModel with one property with this code

    public class UserControl1VM
    {
        public string Message { get; set; }

        public UserControl1VM()
        {
            Message = "JustMessage";
        }
    }


2. Next in UserControl1.xaml

<UserControl x:Class="DataContextTest.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             xmlns:local="clr-namespace:DataContextTest"
             d:DesignHeight="300" d:DesignWidth="300"><!--<UserControl.DataContext><local:UserControl1VM/></UserControl.DataContext>--><Grid Background="Gray"><Label Foreground="White" Content="{Binding Message}" FontSize="25"></Label><Button Height="20" ></Button></Grid></UserControl>

4. Created resource dictionary indicating View and VM

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:DataContextTest"><DataTemplate DataType="{x:Type local:UserControl1VM}"><local:UserControl1 /></DataTemplate><Style TargetType="{x:Type Button}"><Setter Property="Foreground" Value="White" /><Setter Property="Background" Value="Green" /><Setter Property="FontSize" Value="14" /></Style></ResourceDictionary>


3. Merged dictionary in App.xaml.cs

   public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            ResourceDictionary dictionary = new ResourceDictionary();
            dictionary.Source = new Uri("pack://application:,,,/DataContextTest;component/Dictionary1.xaml ");
            Application.Current.Resources.MergedDictionaries.Add(dictionary);

        } 
    }

4. This UserControl1 is part of MainWindow

<Window x:Class="DataContextTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataContextTest"
        Title="MainWindow" Height="500" Width="525" WindowStartupLocation="CenterScreen"><Grid><local:UserControl1 Width="200" Height="200"></local:UserControl1></Grid></Window>

Now the issue is i'm able to see the button style applied to the button in UserControl, but unable to get the datacontext bound. Hence the property 'Message' isn't reflecting the changes that i've set in its constructor.

I'm missing something here..

Just the UI thread, but getting a multithreading related error.

$
0
0
"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

Except I'm not not spawning any additional threads.

I wrote an observable collection that wraps FileSystemWatcher which I then bound to a ListView. When I alter files in the watched folder, the collection updates itself and then fails to raise CollectionChanged with the aforementioned exception. What's wrong?

<Window x:Class="FolderWatcherTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:a="clr-namespace:FolderWatcherTest" Title="Folder Watcher" Width="640" Height="480" WindowStartupLocation="CenterScreen"
    <Window.Resources> 
        <a:FolderWatcher x:Key="watcher"/> 
    </Window.Resources> 
    <ListView ItemsSource="{DynamicResource watcher}"
        <ListView.View> 
            <GridView> 
                <GridViewColumn Header="Name"  DisplayMemberBinding="{Binding Path=Value.Name}"/> 
            </GridView> 
        </ListView.View> 
    </ListView> 
</Window> 

using System; 
using System.Collections; 
using System.Collections.Specialized; 
using System.IO; 
using System.Windows; 
using System.Windows.Controls; 
 
namespace FolderWatcherTest 
    public partial class Window1 : Window 
    { 
        public Window1() 
        { 
            InitializeComponent(); 
        } 
    } 
 
    public class FolderWatcher : DictionaryBase, INotifyCollectionChanged 
    { 
        FileSystemWatcher watcher; 
        public event NotifyCollectionChangedEventHandler CollectionChanged; 
 
        public FolderWatcher() 
        { 
            watcher = new FileSystemWatcher("."); 
            ReloadDictionary(watcher.Path, watcher.Filter); 
            watcher.Changed += new FileSystemEventHandler(watcher_Changed); 
            watcher.Created += new FileSystemEventHandler(watcher_Created); 
            watcher.Deleted += new FileSystemEventHandler(watcher_Deleted); 
            watcher.Renamed += new RenamedEventHandler(watcher_Renamed); 
            watcher.EnableRaisingEvents = true
        } 
 
        void ReloadDictionary(string path, string filter) 
        { 
            Dictionary.Clear(); 
            foreach (string i in Directory.GetFiles(path, filter)) 
            { 
                FileInfo f = new FileInfo(i); 
                Dictionary.Add(f.Name, f); 
            } 
            if (CollectionChanged != null
            { 
                CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 
            } 
        } 
 
        public string Path 
        { 
            get { return watcher.Path; } 
            set 
            { 
                if (watcher.Path != value) 
                { 
                    ReloadDictionary(value, watcher.Filter); 
                    watcher.Path = value; 
                } 
            } 
        } 
 
        public string Filter 
        { 
            get { return watcher.Filter; } 
            set 
            { 
                if (watcher.Filter != value) 
                { 
                    ReloadDictionary(watcher.Path, value); 
                    watcher.Filter = value; 
                } 
            } 
        } 
 
        void watcher_Changed(object sender, FileSystemEventArgs e) 
        { 
            FileInfo f = new FileInfo(e.Name); 
            FileInfo old = this[f.Name]; 
            Dictionary[f.Name] = f; 
            CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, f, old)); 
        } 
 
        void watcher_Created(object sender, FileSystemEventArgs e) 
        { 
            FileInfo f = new FileInfo(e.Name); 
            Dictionary.Add(f.Name, f); 
            CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, f)); 
        } 
 
        void watcher_Deleted(object sender, FileSystemEventArgs e) 
        { 
            FileInfo f = new FileInfo(e.Name); 
            Dictionary.Remove(f.Name); 
            CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, f)); 
        } 
 
        void watcher_Renamed(object sender, RenamedEventArgs e) 
        { 
            FileInfo f = new FileInfo(e.Name); 
            FileInfo old = new FileInfo(e.OldName); 
            Dictionary.Remove(old.Name); 
            Dictionary.Add(f.Name, f); 
            CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, f, old)); 
        } 
 
        public FileInfo this[string key] 
        { 
            get { return (FileInfo)Dictionary[key]; } 
        } 
    } 


Multithreading UI so Listview content is added by a helper thread

$
0
0

Hi,

I'm trying to use a helper thread to add data to a listview. I have implementation working now the next step is to allow the listview to also be grouped by a specific attribute.

So looking at this solution of using the dispatching collection. You can’t change the ItemsSource of the listview more than once and it has to be to the “wrapper” collection. However inorder to group the items you have to set the ItemsSource again to pickup the new grouping…

 

This is beatrize’s (sp) article:

 

http://www.beacosta.com/2006/09/how-can-i-propagate-changes-across.html

 

Here is kent b’s article: (where that zip code sample came from):

 

http://kentb.blogspot.com/

 

Is it really that bizzare that if you set the ItemsSource to something else and then back again before changing the underlying collection that the Add function would throw exceptions yes, yes it is...

 

If you change the ItemsSource of the list view and then try to group it after using the dispatching collection you can no longer safely add items to the list view. The collection will throw exceptions on every add you do stating "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

Am I wrong to think this is a bug on WPF or is there another way to do the grouping while having the ItemsSource = the wrapper collection?

 

Thanks,

Daniel


listbox update

$
0
0

hello,

I have a button that, when clicked, adds an item to a string list that is bound to a listbox. The listbox doesn't get updated when the button is clicked. Is this a normal behaviour ?
I am forced to manually update it using listbox1.Items.Refresh(), how can I make the binding so that the listbox gets automatically refreshed when the list is changed ?
The binding I used is just ItemsSource="{Binding Path=list1}".

 

Thanks.

ListCollectionView Multithreading

$
0
0
Hi. I have a strange problem with ListCollectionView. I have a collection that is bound to an UI. In code i have a ListCollectionView of this collection. I do all the source collection modifications on UI thread but it seems that when i have ListCollectionView of it there is always an exception thrown

A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll
This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

If i remove the ListCollectionView modifications done normaly. Anyone have any idea why this occouring?

WPF threading question

$
0
0

 

I've tried to post this a few times, I wonder why its not working.

 

Hi Everybody,
I would like to add an item to a ListBox from another thread and I've learned that "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

So instead of adding the item from the 2nd thread, I would like to use an AutoResetEvent (or similar) to wake up the main/dispatcher thread and do the work from the main/dispatcher thread. Does anyone know how to do this? Thanks
Patrick

Unit Testing Dependency Properties

$
0
0
Hi,

This week we've been struggling with Unit Test together with WPF Dependency properties. We're programming a WPF Client / Server Application using DevForce of IdeaBlade and the EF. We generate the ViewModel using T4. The Product we build is called KLIB. So far, except for a few hick-ups, this seems all to work pretty good. As good developer-teams should we decided to create Unit Tests for all our code.

We've written a StateMachine that should manage the state of an Entity it contains (has an Entity). The StateMachine has several properties it exposes for WPF to bind to. Here's part of the code of the StateMachine:

	/// <summary>
	/// State machine for the maintenace operations on a VM entity.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public partial class VMMaintenanceStateMachine<T> : StateMachine<MaintenanceState> where T : VMEntity
	{
		#region Static

		public static readonly DependencyProperty CanDeleteProperty =
			DependencyProperty.Register("CanDelete", typeof(bool), typeof(VMMaintenanceStateMachine<T>), new UIPropertyMetadata(false));

		public static readonly DependencyProperty CanCancelProperty =
			DependencyProperty.Register("CanCancel", typeof(bool), typeof(VMMaintenanceStateMachine<T>), new UIPropertyMetadata(true));

		public static readonly DependencyProperty FinishAfterSaveProperty =
			DependencyProperty.Register("FinishAfterSave", typeof(bool), typeof(VMMaintenanceStateMachine<T>), new UIPropertyMetadata(false));

This Class inherits the StateMachine Class. Here's part of that Class:

	/// <summary>
	/// Abstract state machine that works on an enumeration of states. Is a DependencyObject.
	/// </summary>
	public abstract class StateMachine<T> : DependencyObject
	{
		#region Static

		public static readonly DependencyProperty StateProperty =
			DependencyProperty.Register("State", typeof(T), typeof(StateMachine<T>),
										new UIPropertyMetadata(OnStateChanged));

		/// <summary>
		/// The State property was changed
		/// </summary>
		/// <param name="target"></param>
		/// <param name="e"></param>
		protected static void OnStateChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
		{
			StateMachine<T> stateMachine = (StateMachine<T>)target;
			if (stateMachine.m_FireStateChangedEvent)
			{
				stateMachine.OnStateChanged();
			}
		}

		#endregion



Dependency Properties are by design 'static' now we believe that here lies our problem. When we create more than 1 Unit Test for these kind of properties the 'static' variable is fired only once (which is normal). The test however expects the code to be reentrant which would mean that for every test the static property is initialized again. When we start the tests seperately (using the 'Run Tests in current context') they pass errorfree. We've bundled all the tests in an 'ordered test' to prevent them from running multitreaded (WPF is, as you all probably know, not thread save).

Because the 'static' dependency property is only fired once, succesive tests start running with the wrong default value. We've searched the web for many hours and found several entries about this problem but no satifying answers so far. That's why we turn to MSDN.

Questions:
- Can we use MSTest to run Unit Tests for Dependency Properties?
- We've found an entry on the Web stating we could create a new AppDomain for ever test we want to run. If that is a solution, how is it done?
- Would NUnit be an alternative to MSTest?
- Any input you can give us on solving this problem.

Versions:
- Visual Studio 2008 Professional SP1
- .NET 3.5
- Windows Vista

Regards,
Paul Sinnema
Diartis AG
Switzerland
Take a look at the site of my employer: http://www.diartis.ch

Onclick button from ItemTemplate

$
0
0

Hello , i am working on Listbox.
In my Listbox , i display Name of product, quantity  price and Total.
i am using  Textblock to display these details in my Listitem Template. 
I am using Database as source
I customize the listbox like this

<ListBox x:Name="cartGrid"  Grid.Row="1" BorderThickness="0" BorderBrush="{x:Null}" ><ListBox.ItemTemplate><DataTemplate><Border BorderBrush="#FFD9D9D9"  Margin="30,1,30,0" BorderThickness="0,0,0,1" Padding="0,10,0,20" Width="750" ><StackPanel  Orientation="Vertical" HorizontalAlignment="Stretch"  ><TextBlock     TextWrapping="Wrap"  Text="{Binding col_Name}"   Margin="5,26,10,0" FontSize="18" HorizontalAlignment="Stretch"/><TextBlock  FontWeight="Normal"   HorizontalAlignment="Stretch"  Foreground ="#FF212121"   Margin="5,10,5,0" FontSize="11" VerticalAlignment="Top"><TextBlock.Inlines><Run   FontSize="11" Text="Price: " /><Run   FontSize="11" Text="{Binding col_price}" /></TextBlock.Inlines></TextBlock> <TextBlock  FontWeight="Normal"   HorizontalAlignment="Stretch"  Foreground ="#FF212121"   Margin="5,10,5,0" FontSize="11" VerticalAlignment="Top"><TextBlock.Inlines><Run   FontSize="11" Text="Quantity: " /><Run   FontSize="11" Text="{Binding col_qte}" /><Button Margin="0,0,0,4"  ToolTip="Delete"    Style="{StaticResource myStyle3}"  Click="Edit_Click" Background="{x:Null}" >Edit     </Button></TextBlock.Inlines></TextBlock> <TextBlock  FontWeight="Normal"   HorizontalAlignment="Stretch"  Foreground ="#FF212121"   Margin="5,10,5,0" FontSize="11" VerticalAlignment="Top"><TextBlock.Inlines><Run   FontSize="11" Text="Total: " /><Run   FontSize="11" Text="{Binding col_total}" /><Button Margin="0,0,0,4"  ToolTip="Delete"    Style="{StaticResource myStyle3}"  Click="Delete_Click" Background="{x:Null}" >Delete    </Button></TextBlock.Inlines></TextBlock> </StackPanel></Border></DataTemplate></ListBox.ItemTemplate></ListBox>

I have Edit Button and Delete Button in each ListBoxitem.

onclick on Delete Button, i want to get the item selected Index , then i can remove that in the Listview.


onclick on Edit Button, only the target listitem will enable to edit and 
i want to change the textblock into combobox, for   allow user to change the quantity.  from there I can do the rest  myself

Thanks in advance for your help.

How do I add items to a bound ObservableCollection in another thread?

$
0
0
I want this piece of code

foreach (TransactionLogModel transactionLog in transactionLogList)
     _MyObservableCol.Add(transactionLog);

to be executed in another thread. I want to have an effect wherein the listview (gridview) is seen being populated one by one and the UI is not blocked. I tried using async delegates but _MyObservableCol is from UI thread so it throws an exception. I can easily update the listview using SynchronizationContext but it won't have the effect of the listview being populated one-by-one. Instead, the UI will be bolcked and the listview will display the entire data on one swoop. How can I get this effect?

Resources in Xaml, WPF

$
0
0

I am currently developing animation of pigs in my software. However, there's one thing that I'm not sure. Every pig in my program is a usercontrol and there are some animations, pictures in the xaml resources of the pig control.  As there are many pigs in my UI, are those resources shared in all my pig control? or there are as many copies of those pictures as the pig controls?

Moreover, I animate the pigs by changing the opacity of the pictures. Sometimes I would like to change the frame rate. But I have to manually change a lot of properties. How can I excute arithmetic operations like addition in setting the properties?

For example, below is part of my animation. By defining Keytime, I can change my frame rate. However, each time I would like to change the frame rate, I have to change a lot of  keytime manually. They are just times of 0.05.

Would you please provide some suggestions so that I can simplify my work?

<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="IMG_pig_SW1" Duration="0:0:0.8"><DiscreteDoubleKeyFrame KeyTime="0" Value="1"/><DiscreteDoubleKeyFrame KeyTime="0:0:0.05" Value="0"/><DiscreteDoubleKeyFrame KeyTime="0:0:0.75" Value="1" /></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="IMG_pig_SW2" Duration="0:0:0.8"><DiscreteDoubleKeyFrame KeyTime="0:0:0.05" Value="1"/><DiscreteDoubleKeyFrame KeyTime="0:0:0.1" Value="0"/><DiscreteDoubleKeyFrame KeyTime="0:0:0.7" Value="1" /><DiscreteDoubleKeyFrame KeyTime="0:0:0.75" Value="0" /></DoubleAnimationUsingKeyFrames>


Add a function that will be executed automatically after a certain date in WPF, resultantly temporarily deactivating the user account

$
0
0
Hi. I am developing a a Library Management System in WPF with SQL Server 2008 r2 at the back-end. I want to put such functionality in the WPF application that that when a borrower does not return the book after specified days i.e 14 days, the borrowers account must be deactivated automatically until the borrower doesnot return the book. How to make this possible.

CompositePresentationEvent order of execution

$
0
0

If i publish multiple events in a single threaded environment, in what order will the subscribers be invoked?

for intance,

Event 1

UpdateCartEventArgs args = new UpdateCartEventArgs (param);
eventAggregator.GetEvent<UpdateCartEventArgs >().Publish(args);

Event 2

eventAggregator.GetEvent<RunTotalEvent>().Publish(
                     new RunTotalEventEventArgs(param));

In which order will the subscribers be called? Is it guarenteed (in a single threaded environment) that Event 1's subscriber will be invoked before event 2?


Anonymous

Viewing all 18858 articles
Browse latest View live


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