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

How to bind Pie Chart to a Datasource

$
0
0

Hello all, 

My goal is to display my database table values ( I have two columns as Total and Used)  on a pie chart. I  used the WPFToolkit for the chart control and created a pie chart structure.

but I am stuck with binding the chart to the datasource. 

Any one can pls suggest me a solution. Thanks ! 





WPF application throws null reference exception when application is minimized

$
0
0

We have a very large windows application running on Windows XP SP 3 created from VS2010 Premium 10.0.30319.1  and .NET 4.0.30319. The application uses WPF code to specify how the UI looks. There is a panel with a lot of tabs all with WPF XAML definitions, etc.

It works fine except that if you try to minimize the application while there are elements in a grid inside one of the tabs (just the one grid, the other grids don't seem to have the problem), there is a null reference exception thrown from (apparently) WPF. We can't debug in there and we can't figure out how to catch the exception either. I wonder if anyone has any ideas on how to find out what is happening. Maybe someone knows of hotfixes to WPF available in VS2010 (we can't upgrade to 2012 for a variety of reasons). Thanks.

I don't seem to be able to paste in the exception (maybe a restriction in the forum?). 


Dave Griffin


Hopefully this other computer will let me post the exception System.NullReferenceException was unhandled Message=Object reference not set to an instance of an object. Source=PresentationFramework StackTrace: at System.Windows.Controls.ItemContainerGenerator.Remove(GeneratorPosition position, Int32 count, Boolean isRecycling) at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IRecyclingItemContainerGenerator.Recycle(GeneratorPosition position, Int32 count) at System.Windows.Controls.VirtualizingStackPanel.CleanupRange(IList children, IItemContainerGenerator generator, Int32 startIndex, Int32 count) at System.Windows.Controls.VirtualizingStackPanel.CleanupContainers(Int32 firstViewport, ItemsControl itemsControl) at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint) at System.Windows.Controls.Primitives.DataGridRowsPresenter.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) at System.Windows.Controls.ItemsPresenter.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) at System.Windows.Controls.ScrollContentPresenter.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV) at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV) at System.Windows.Controls.Grid.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.ScrollViewer.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.Border.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.Control.MeasureOverride(Size constraint) at System.Windows.Controls.DataGrid.MeasureOverride(Size availableSize) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV) at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV) at System.Windows.Controls.Grid.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) at System.Windows.Controls.ContentPresenter.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.Border.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.Control.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Controls.DockPanel.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Documents.AdornerDecorator.MeasureOverride(Size constraint) at System.Windows.FrameworkElement.MeasureCore(Size availableSize) at System.Windows.UIElement.Measure(Size availableSize) at System.Windows.Interop.HwndSource.Process_WM_SIZE(UIElement rootUIElement, IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam) at System.Windows.Interop.HwndSource.LayoutFilterMessage(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 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(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.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.SafeNativeMethods.SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at System.Windows.Forms.Integration.ElementHost.SetHWndSourceWindowPos() at System.Windows.Forms.Integration.ElementHost.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) at System.Windows.Forms.Layout.DefaultLayout.xLayoutDockedControl(IArrangedElement element, Rectangle newElementBounds, Boolean measureOnly, Size& preferredSize, Rectangle& remainingBounds) at System.Windows.Forms.Layout.DefaultLayout.LayoutDockedControls(IArrangedElement container, Boolean measureOnly) at System.Windows.Forms.Layout.DefaultLayout.xLayout(IArrangedElement container, Boolean measureOnly, Size& preferredSize) at System.Windows.Forms.Layout.DefaultLayout.LayoutCore(IArrangedElement container, LayoutEventArgs args) at System.Windows.Forms.Layout.LayoutEngine.Layout(Object container, LayoutEventArgs layoutEventArgs) at System.Windows.Forms.Control.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.ScrollableControl.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty) at System.Windows.Forms.Control.OnResize(EventArgs e) at System.Windows.Forms.Panel.OnResize(EventArgs eventargs) at System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight) at System.Windows.Forms.Control.UpdateBounds() at System.Windows.Forms.Control.WmWindowPosChanged(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.TabPage.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.SetBounds(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.set_Bounds(Rectangle value) at System.Windows.Forms.TabControl.UpdateTabSelection(Boolean updateFocus) at System.Windows.Forms.TabControl.OnResize(EventArgs e) at System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight) at System.Windows.Forms.Control.UpdateBounds() at System.Windows.Forms.Control.WmWindowPosChanged(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.TabControl.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) at System.Windows.Forms.Layout.DefaultLayout.xLayoutDockedControl(IArrangedElement element, Rectangle newElementBounds, Boolean measureOnly, Size& preferredSize, Rectangle& remainingBounds) at System.Windows.Forms.Layout.DefaultLayout.LayoutDockedControls(IArrangedElement container, Boolean measureOnly) at System.Windows.Forms.Layout.DefaultLayout.xLayout(IArrangedElement container, Boolean measureOnly, Size& preferredSize) at System.Windows.Forms.Layout.DefaultLayout.LayoutCore(IArrangedElement container, LayoutEventArgs args) at System.Windows.Forms.Layout.LayoutEngine.Layout(Object container, LayoutEventArgs layoutEventArgs) at System.Windows.Forms.Control.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.ScrollableControl.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.ContainerControl.OnLayout(LayoutEventArgs e) at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty) at System.Windows.Forms.Control.OnResize(EventArgs e) at System.Windows.Forms.UserControl.OnResize(EventArgs e) at System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight) at System.Windows.Forms.Control.UpdateBounds() at System.Windows.Forms.Control.WmWindowPosChanged(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.UserControl.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) at System.Windows.Forms.Layout.DefaultLayout.xLayoutDockedControl(IArrangedElement element, Rectangle newElementBounds, Boolean measureOnly, Size& preferredSize, Rectangle& remainingBounds) at System.Windows.Forms.Layout.DefaultLayout.LayoutDockedControls(IArrangedElement container, Boolean measureOnly) at System.Windows.Forms.Layout.DefaultLayout.xLayout(IArrangedElement container, Boolean measureOnly, Size& preferredSize) at System.Windows.Forms.Layout.DefaultLayout.LayoutCore(IArrangedElement container, LayoutEventArgs args) at System.Windows.Forms.Layout.LayoutEngine.Layout(Object container, LayoutEventArgs layoutEventArgs) at System.Windows.Forms.Control.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.ScrollableControl.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty) at System.Windows.Forms.Control.OnResize(EventArgs e) at System.Windows.Forms.Panel.OnResize(EventArgs eventargs) at System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight) at System.Windows.Forms.Control.UpdateBounds() at System.Windows.Forms.Control.WmWindowPosChanged(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) at System.Windows.Forms.Layout.DefaultLayout.xLayoutDockedControl(IArrangedElement element, Rectangle newElementBounds, Boolean measureOnly, Size& preferredSize, Rectangle& remainingBounds) at System.Windows.Forms.Layout.DefaultLayout.LayoutDockedControls(IArrangedElement container, Boolean measureOnly) at System.Windows.Forms.Layout.DefaultLayout.xLayout(IArrangedElement container, Boolean measureOnly, Size& preferredSize) at System.Windows.Forms.Layout.DefaultLayout.LayoutCore(IArrangedElement container, LayoutEventArgs args) at System.Windows.Forms.Layout.LayoutEngine.Layout(Object container, LayoutEventArgs layoutEventArgs) at System.Windows.Forms.Control.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.ScrollableControl.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.Form.OnLayout(LayoutEventArgs levent) at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args) at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty) at System.Windows.Forms.Control.OnResize(EventArgs e) at System.Windows.Forms.Form.OnResize(EventArgs e) at System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight) at System.Windows.Forms.Control.UpdateBounds() at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Form.DefWndProc(Message& m) at System.Windows.Forms.Control.WmWindowPosChanged(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Form.DefWndProc(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Form.WmSysCommand(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Form.DefWndProc(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ContainerControl.WndProc(Message& m) at System.Windows.Forms.Form.WmNcButtonDown(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at ApplicationFrame.MainFrame.Main() in C:\Documents and Settings\Galaxy\Desktop\C5RAKS352R\PCIU_CSCI\UserInterfaceComponents\MainFrame.cs:line 1169 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

Checkbox in Datagrid to set background color of row.

$
0
0

I'm trying to change the background color of a grid depending on which of two check boxes are checked.  Once I've selected rows in the grid I want to use the data to make an insert to a different table with one field's value being dependent on which of the two check boxes are selected in the grid.  Below is my current code.  I've attempted several thing without success.  

XAML:

<Window x:Class="TESTWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525"><Grid><Button Content="Button" HorizontalAlignment="Left" Margin="43,35,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1" RenderTransformOrigin="0.507,0.545"/><DataGrid Name="dg"
                  HorizontalAlignment="Left" 
                  Margin="10,81,0,0" 
                  VerticalAlignment="Top" 
                  Height="214"                   
                  AutoGenerateColumns="False"
                  ScrollViewer.VerticalScrollBarVisibility="Auto" Width="497"><DataGrid.Columns><DataGridTemplateColumn Header="OK" Width="40"><DataGridTemplateColumn.CellTemplate><DataTemplate><CheckBox Name="OKCCheckBox" 
                                      HorizontalAlignment="Center" 
                                      IsChecked="{Binding Path=NONC, UpdateSourceTrigger=PropertyChanged}"
                                      /></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn><DataGridTextColumn Header="RMA ID"
                                    Width="80"
                                    Binding="{Binding Path=RMA_ID}"
                                    /><DataGridTextColumn Header="SERIAL #"
                                    Width="80"
                                    Binding="{Binding Path=SERIAL_ID}"
                                    /><DataGridTextColumn Header="PART #"
                                    Width="150"
                                    Binding="{Binding Path=INV_ITEM_ID_ORDERED}"
                                    /><DataGridTextColumn Header="QTY"
                                    Width="50"
                                    Binding="{Binding Path=QTY}"
                                    /><DataGridTemplateColumn Header="NonC" Width="40"><DataGridTemplateColumn.CellTemplate><DataTemplate><CheckBox Name="NONCCheckBox" 
                                      HorizontalAlignment="Center" 
                                      IsChecked="{Binding Path=NONC, UpdateSourceTrigger=PropertyChanged}"
                                      /></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn></DataGrid.Columns><DataGrid.RowStyle><Style TargetType="DataGridRow"><Setter Property="Background" Value="Beige"/><Style.Triggers><Trigger Property="IsMouseOver" Value="true"><Setter Property="Background" Value="Bisque"/></Trigger><Trigger Property="IsSelected" Value="true"><Setter Property="Background" Value="Bisque"/></Trigger><DataTrigger Binding="{Binding Path=RMA_ID}" Value="HJRA0000P4"><Setter Property="Background" Value="Green"/></DataTrigger></Style.Triggers></Style></DataGrid.RowStyle></DataGrid></Grid></Window>

C# code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using Oracle.DataAccess.Client;

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

        public DataSet GetItemInformationRMAID()
        {
            string _connstring = "Data Source=ORCL;User Id=TEST;Password=TEST;";
            string _sql;
            DataSet _ds = new DataSet();
            try
            {
                OracleConnection _connObj = new OracleConnection(_connstring);
                _connObj.Open();
                _sql = "select rma_id, serial_id, inv_item_id_ordered, qty from return_line";
                OracleDataAdapter _adapterObj = new OracleDataAdapter();
                OracleCommand cmd = new OracleCommand(_sql, _connObj);
                _adapterObj.SelectCommand = cmd;
                _adapterObj.Fill(_ds);
                _connObj.Close();
                _connObj.Dispose();
                _connObj = null;
                return _ds;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return _ds;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            dg.ItemsSource = GetItemInformationRMAID().Tables[0].DefaultView;
        }
    }
}

I'm sure I'm missing something obvious, but being a newbie I'm just not seeing it.  Any help is appreciated.

Thanks,

Magnus


Print Preview like control which handler Column Overflow using WPF DataGrid

$
0
0

Hi,

I have 100 records of student and each contains 50 properties(Attributes) ex (Name,Roll No, Address, Mob No. etc).

Now I want to show these records in the table format as:

I am considering Paper Size as A4,

Suppose number of columns can be displayed on A4 page are 25

and number of Rows can be displayed are 60

Now I want to create seperate pages as:

Page Number 1 will show first 60 rows with 1 to 25 columns

page number 2 will show 61 to 100 with same 1 to 25 columns

Now Page number 3 will show first 60 rows with 25 to 50 columns

and Page number 4 will show 61 to 100 rows with 25 to 50 columns.

This is something similar to Excel: when we try to print more columns which can't be fit on page.

Note: I want to show all the pages in scroll viewer , not like we show in FlowDocumentViewer.

How I can achieve this?


Wajeed


Refresh Datagrid when Datasource is updated

$
0
0
I have a data grid that displays a Table which is bound to a DataSourcewhich keeps changing on a time constraint. 
How to refresh the data grid's content when my DataSource values are updated.

P.S : The values in my DataSource Tables are updated by a monitoring system. Its table values are updated in regular intervals. 

Where should I add my Observable Collection in my EF ?

      
private IQueryable<MyTable> GetMyTablesQuery(TestDBEntities1 testDBEntities1 )
{       
System.Data.Objects.ObjectQuery<EF_demo1.MyTable> myTablesQuery = testDBEntities1.MyTables;
// Returns an ObjectQuery.
return myTablesQuery ;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
var testDBEntities1 = new EF_demo1.HMDBEntities1();

// Load data into MyTables. You can modify this code as needed.
var eventLogsViewSource =((System.Windows.Data.CollectionViewSource)(this.FindResource("myTablesViewSource")));

IQueryable<EF_demo1.MyTable> myTablesQuery = this.myTablesViewSource(testDBEntities1 );

myTablesViewSource.Source = myTablesQuery .ToList();
}


Cleaning up WindowsFormsHost in a WPF dialog

$
0
0

Hi, I have a windows forms project, where I use a number WPF dialogs (ie a window which I call ShowDialog()). One in particular has a WindowsFormsHost control (to host a windows forms control)

I am using Dev studio 2010, and .net 4.0.

I have been tracking memory leaks (using a 3rd party tool), and have noticed that my WPF dialog is being held in memory! It appears to be something to be with an event handler "ProcessInputEventHandler" of the WindowFormsHost that has has not been removed (see below is a diagram I get from my memory tracking tool).

 

I have tried calling Dispose on the WindowFormsHost control, as well as the control it contains (MaskedTextBox), but it did not fix anything. Has anyone else come across this, and know of any solution?

 

Thanks in advance for any help.

regards

Peter

 


XamlParseException when loading ResourceDictionary

$
0
0

I have a WPF assembly including a window. When opening the window in an WPF application, it works fine.

But when I use the assembly as a part of a plugin for a third-party-software, and I' trying to open the window, I got this exception:

XamlParseException "The method or operation is not implemented."

 
  at System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlType(BamlType bamlType, Int16 typeId)   at System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType(Int16 typeId)   at System.Windows.Baml2006.Baml2006SchemaContext.GetProperty(Int16 propertyId, XamlType parentType)   at System.Windows.Baml2006.Baml2006Reader.Process_PropertyComplexStart()   at System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord()   at System.Windows.Baml2006.Baml2006Reader.ReadObject(KeyRecord record)   at System.Windows.ResourceDictionary.CreateObject(KeyRecord key)   at System.Windows.ResourceDictionary.OnGettingValue(Object key, Object& value, Boolean& canCache)   at System.Windows.ResourceDictionary.OnGettingValuePrivate(Object key, Object& value, Boolean& canCache)   at System.Windows.ResourceDictionary.GetValueWithoutLock(Object key, Boolean& canCache)   at System.Windows.ResourceDictionary.GetValue(Object key, Boolean& canCache)   at System.Windows.ResourceDictionary.get_Item(Object key)   at BuildingEditor.Converter.EnumToResourceConverter.Convert(Object value, Type targetType, Object parameter, CultureInfo culture) in C:\Temp\_temp\_merged\BuildingEditor\Converter\EnumToResourceConverter.cs:line 56   at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)   at System.Windows.Data.BindingExpression.Activate(Object item)   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)   at System.Windows.Data.BindingExpression.AttachOverride(DependencyObject target, DependencyProperty dp)   at System.Windows.Data.BindingExpressionBase.OnAttach(DependencyObject d, DependencyProperty dp)   at System.Windows.StyleHelper.GetInstanceValue(UncommonField`1 dataField, DependencyObject container, FrameworkElement feChild, FrameworkContentElement fceChild, Int32 childIndex, DependencyProperty dp, Int32 i, EffectiveValueEntry& entry)   at System.Windows.FrameworkTemplate.ReceivePropertySet(Object targetObject, XamlMember member, Object value, DependencyObject templatedParent)   at System.Windows.FrameworkTemplate.<>c__DisplayClass6.<LoadOptimizedTemplateContent>b__4(Object sender, XamlSetValueEventArgs setArgs)   at System.Xaml.XamlObjectWriter.OnSetValue(Object eventSender, XamlMember member, Object value)   at System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent)   at System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx)   at System.Xaml.XamlObjectWriter.Logic_AssignProvidedValue(ObjectWriterContext ctx)   at System.Xaml.XamlObjectWriter.WriteEndObject()   at System.Xaml.XamlWriter.WriteNode(XamlReader reader)   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)

The inner exception is a NotImplementedException without any information about what happens there.

(It seems that when opening the window, it tries to load a ResourceDictionary from a XAML file containing some controls. Seems to me that resolving the namespace of the controls is the cause of the problems, but I don't know why it works in a WPF application but not as part of a plugin. All needed assemblies and namespaces are included or referenced by the assembly).

Can you help me finding the cause of this exception?

Best regards,
Christian


Custom Color in WPF?

$
0
0

 Is it possible to display the color of the code that is entered into a textbox by a user?  ex.  User enters #FF0000 and it would display like this -> #FF0000

 


Setting WPF UI Permissions in code-behind

$
0
0

I am looking to see if I can do the following in WPF:

A user opens the WPF application and using the users AD name I will check the users role(s) in a custom DB. This will be something similar to asp.net membership db.

Depending on the user role the WPF will show certain controls.

So for example, if I was an Admin then I would have access to everything but if I was read-only user then I would have limited access to the application.

I know I can set the visibility using the following example:

public class RoleToVisibilityConverter : MarkupExtension,IValueConverter
{
    public RoleToVisibilityConverter()
    {

    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var principal = value as GenericPrincipal;
        bool IsValidUser = false;
        if (principal != null)
        {
            foreach (String role in parameter.ToString().Split(';'))
            {
                if (principal.IsInRole(role))
                {
                    IsValidUser = true;
                    break;
                }  
            }
            return IsValidUser ? Visibility.Visible : Visibility.Collapsed;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

And in the XAML I add the following binding for visibility

Visibility="{Binding Source={x:Static systhread:Thread.CurrentPrincipal}, ConverterParameter=admin;editor;readonly, Converter={rv:RoleToVisibilityConverter}}

But what I want to do is to not have to add this in xaml.

I would like to be able to get the users role and all of it's permissions and depending on the window load the UI permissions.

Reason is that I would like to be able to change what a read-only role can see/do without having to change the xaml.

Does anyone know if this is possible and if so is it best practice.

Thanks in advance.

Noel




Getting the position of a TreeViewItem when BringInToView has been invoked

$
0
0


Hello there.

I have a TreeView with a fair amount of TreeViewItems.

I want to draw a line from a point to a specific item (regardless of its depth in the TreeView).

Therefor, I find the Item in question, call BringInToView and call TransformToAncestor to get the position. This often does exactly what I want but....

When the Item is not visible and the Treeview has to scroll then the Point i get from TransforToAncestor gives me the position that the item had BEFORE it was scrolled (Thus making my line go way of screen)

It seams to me that some kind of refreshing is needed between the BringInToView and the getting of the position? If I try to get the position again (With no scrolling needed) the position is corect.

Can anyone point me in the right direction?

Sourcecode below:

private void Window_Loaded(object sender,RoutedEventArgs e)

        {

            for (int i = 0; i < 50; i++)

            {

               TreeViewItem tvi = newTreeViewItem();

                tvi.Header ="Father #"+ i.ToString();

                treeView1.Items.Add(tvi);

                for (int j = 0; j < 3; j++)

                {

                   TreeViewItem tvj = newTreeViewItem();

                    tvj.Header ="Child #"+ i.ToString();

                    tvi.Items.Add(tvj);

                }

            }

           

        }

        private void button1_Click(object sender,RoutedEventArgs e)

        {

           TreeViewItem tviTemp = (TreeViewItem)treeView1.Items[35];

           TreeViewItem tvi1 = (TreeViewItem)tviTemp.Items[1];

            tvi1.BringIntoView();

                       

           Line l = newLine();

            l.Stroke = newSolidColorBrush(Colors.Black);

            grdMain.Children.Add(l);

            l.X1 = 0;

            l.Y1 = 0;

           GeneralTransform myTransform = tviTemp.TransformToAncestor(treeView1);

           Point myOffset = myTransform.Transform(newPoint(0, 0));

            l.X2 = myOffset.X+30;

            l.Y2 = myOffset.Y;

           

        }

 

Hyperlink control? Getting that blue text with the hovering hand that you click on to open URL

$
0
0

So, this is probably mindless, but, I still don't know how to do it.

I need to place a blue text hyperlink with the hovering hand that when you click on it it opens a browser with a specific address.

Is there a control or a font to create the visual link on the screen (WPF/C#)

How can I open a browser to a specific address from within C# code?

Michael


Michael

Binding combo box in user control does not work but regular combobox works

$
0
0

I have user control that contains a textblock and a combo box as shown below:

<UserControl .... Name="myReusableControl"><TextBlockDockPanel.Dock="Left"x:Name="label">Title:/TextBlock><ComboBoxx:Name="comboBox"></ComboBox></UserControl>

I have added the following the following for the code behind of the user control.

public partial class ctlCombobox : UserControl
    {

    public static readonly DependencyProperty DisplayMemberPathProperty = DependencyProperty.Register("DisplayMemberPath", typeof(string), typeof(ctlCombobox), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true }); 
    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(ctlCombobox), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });          
    public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register("SelectedIndex", typeof(int), typeof(ctlCombobox), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(ctlCombobox), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
    public static readonly DependencyProperty SelectedValuePathProperty = DependencyProperty.Register("SelectedValuePath", typeof(string), typeof(ctlCombobox), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
    public static readonly DependencyProperty SelectedValueProperty = DependencyProperty.Register("SelectedValue", typeof(object), typeof(ctlCombobox), new FrameworkPropertyMetadata(OnSelectedValueChanged) { BindsTwoWayByDefault = true });


    public ctlCombobox()

    {
        InitializeComponent();

        Binding selectedIndexBinding = new Binding("SelectedIndex") { Source = this, Mode = BindingMode.TwoWay };
        Binding itemsSourceItemBinding = new Binding("ItemsSource") { Source = this, Mode = BindingMode.TwoWay };
        Binding displayMemberPathBinding = new Binding("DisplayMemberPath") { Source = this, Mode = BindingMode.OneWay };
        Binding selectedItemBinding = new Binding("SelectedItem") { Source = this, Mode = BindingMode.TwoWay };
        Binding selectedValueBinding = new Binding("SelectedValue") { Source = this, Mode = BindingMode.TwoWay };
        Binding selectedValuePathBinding = new Binding("SelectedValuePath") { Source = this, Mode = BindingMode.TwoWay };

        comboBox.SetBinding(ComboBox.SelectedIndexProperty, selectedIndexBinding);
        comboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSourceItemBinding);
        comboBox.SetBinding(ComboBox.DisplayMemberPathProperty, displayMemberPathBinding);
        comboBox.SetBinding(ComboBox.SelectedItemProperty, selectedItemBinding);
        comboBox.SetBinding(ComboBox.SelectedValueProperty, selectedValueBinding);
        comboBox.SetBinding(ComboBox.SelectedValuePathProperty, selectedValuePathBinding);
    }


    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    [Browsable(true)]
    public int SelectedIndex
    {
        get { return (int)GetValue(SelectedIndexProperty); }
        set { SetValue(SelectedIndexProperty, value); }
    }

    [Browsable(true)]
    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    [Browsable(true)]
    public object SelectedValue
    {
        get { return (object)GetValue(SelectedValueProperty); }
        set { SetValue(SelectedValueProperty, value); }
    }

    [Browsable(true)]
    public string SelectedValuePath
    {
        get { return (string)GetValue(SelectedValuePathProperty); }
        set { SetValue(SelectedValuePathProperty, value); }
    }

I make reference to the control above in my main control as shown below:

<UserControl Name="mainControl" ...>       <DataGrid Name="lvEmployee" ItemsSource="{Binding Path=Employees, Mode=TwoWay}"  <DataGrid.Columns>                <DataGridTextColumn Header="Employee Type" Width="7*" Binding="{Binding Path=EmployeeType.Name}" />                <DataGridTextColumn Header="First Name" Width="8*" Binding="{Binding Path=FirstName}" />                <DataGridTextColumn Header="Middle Name" Width="8*" Binding="{Binding Path=MiddleName}" />                <DataGridTextColumn Header="Last Name" Width="9*" Binding="{Binding Path=LastName}" />             </DataGrid.Columns>         <DataGrid.RowDetailsTemplate><DataTemplate>                    <cc:ctlCombobox x:Name="cmbEmployeeType" 
                 ItemsSource="{Binding Source={x:Reference mainControl}, Path=DataContext.EmployeeTypes}"          
                 DisplayMemberPath="Name" SelectedValuePath="Id"   SelectedValue="{Binding   
                 Path=EmployeeTypeId}"  "></cc:ctlCombobox></DataTemplate></DataGrid.RowDetailsTemplate></DataGrid>	</UserControl>

The issue is the  with cc:ctlComboboxx:Name="cmbEmployeeType". It should function as a look up where it is populated with all  the possible EmployeeTypes. However, when I try to bind to Employee.EmployeeTypeId (datacontext is Employee object),  the combobox is not selected.

I have no error in output. Additionally, the binding works if I use a plain combobox and also my bindings work for textbox user controls inside the datatemplate. I am using the MVVM pattern.

Can we Add one more property in TextBox

$
0
0

Hi,

I have textbox and spread every where in my Application,

but would like to add one more property which set for numeric textbox and i can avoid to enter character.

or can you suggest me to make less change and make this kind of workable.

I can use Texbox_keydown and then e.handle but i dont want to add this event for each textbox like that.

pls suggest some thing better.

Thanks

A-


Ashok

Cancel Datagrid AddRow

$
0
0

The DataGrid is tied to a DataView of a DataSet.  If the user starts to add a row and then exits the window they can leave behind a row with a duplicate key or null key.  This leaves a transaction in progress.  When they try and open the window again there is an exception:

       'DeferRefresh' is not allowed durning an AddNew or EditItem transaction.

Two choices:

1.  How can I cancel the transaction on closing the window if something is invalid?

2.  How can I cancel a pending transaction on opening the window? I have been able to trap this error.

Application.Shutdown() confirmation window

$
0
0

I have a wpf project which has couple of windows, whne i navigate from one window to other i just  hide one window and create instance of other if not created already

in all windows there is window closing event handler

    private void Window_Closing_1(object sender, CancelEventArgs e)
        {
             {
            string message = "You are trying to close window " + this.Name + " .Are you sure?";
            string caption = "Exit";
            MessageBoxButton buttons = MessageBoxButton.YesNo;
            MessageBoxImage icon = MessageBoxImage.Question;
            if (MessageBox.Show(message, caption, buttons, icon) == MessageBoxResult.Yes)
            {
                App.Current.Shutdown();
            }
            else
            {
             MessageBox.Show("Closing aborted");

            }
        }
but problem is this event is there in every window so when i close it lots of other prompt from other window also show up. Is there a way to avoid other pronpts if i close in only one window?


Changing icons in a ClickOnce update

$
0
0

When I launch my ClickOnce apps, during the stage of Launching Application, ClickOnce checks to see if I posted updates:

The icon that is displayed in the Task Bar is really ugly and conveys no information about the application that is being updated:

Is there a way to change this icon? Maybe to one that is associated with the application that I'm installing?

Michael


Michael

How to implement a Menu/Page style application?

$
0
0

Excuse me if I'll not be very clear ;-)

this is my very first project with WPF

I'd like to implement an application with a menu on the left side (a list of buttons)

Left Menu

- NEW

- UPDATE

- DELETE

- CONFIGURATION

and interchangeable views (Windows "docked" on a component) on the right.

Each view/window perform a completely different task, with his own controls, ecc...

I say Windows because so I can have the code for each window clearly separated, i don't want to mix all code in one big file...

How would you implement this?

Up to now my starting solution is like this:

When a User clicks on a Menu Button

       
privatevoid buttonVisualizzaScheda_Click(object sender, RoutedEventArgs e)        {            DockWindowRightGrid(new Test.TestDynamicLayout(), sender asButton);        }        privateButton activeButton = null;        privateWindow activeWindow = null;        privatevoid DockWindowRightGrid(Window newWindow, Button callingButton)        {            if (activeButton != null)            {                //activeButton.Background = Button.DefaultStyleKeyProperty; // How to restore default color???            }            activeButton = callingButton;            activeButton.Background = newSolidColorBrush(Colors.DodgerBlue); // Active button color
              
if (activeWindow != null)            {                activeWindow.Close();            }            activeWindow = newWindow;            activeWindow.WindowStyle = System.Windows.WindowStyle.None;            activeWindow.BorderThickness = newThickness(0);            activeWindow.Owner = this;            activeWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;            activeWindow.Left = this.Left + 200;            activeWindow.Top = this.Top + 90;            activeWindow.AllowsTransparency = true;            activeWindow.Width = gridContent.Width;            activeWindow.Height = gridContent.Height;            activeWindow.Show();        }

ONE BIG PROBLEM YET!

When the User moves the Main Window, because the actual activeWindow ins't really attached to the Main, it remains hanging in the center of the screen!!!

PS: this bug alone, let me think that mine isn't exactly the best approach I could take!!!

.exe VS2012 issue

$
0
0

Hi,

Can anybody follow-up on the below mentioned post?

http://social.msdn.microsoft.com/Forums/en-US/netfxsetup/thread/439e6c4d-a7fc-4318-914e-597622762bcb/#85ca8cde-6407-4d81-9a61-77662feb0614

Thanks

Chinmay

Binding Datagrid to a database using Observable collection ( MVVM pattern & developing in c#)

$
0
0

I am trying to bind a datagrid from a Database table using Observablecollection. when I came across a similar post- link on this forum , I tried to implement it on my project. but still, I am struggling to have a proper result. 

here is my code , kindly help me to find where I have gone wrong ? 

XAML :

<Window x:Class="MVVM_DemoAppl.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ViewModel="clr-namespace:MVVM_DemoAppl.ViewModels" Title="MainWindow" Height="350" Width="525">

<Window.DataContext><ViewModel:MainViewModel/></Window.DataContext><Grid><DataGrid ItemsSource="{Binding SystemStatusData}" AutoGenerateColumns="False" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479" ><DataGrid.Columns><DataGridTextColumn Header="System" Width="auto" Binding="{Binding System}" /><DataGridTextColumn Header="Date" Width="auto" Binding="{Binding Date}"/><DataGridTextColumn Header="Type" Width="auto" Binding="{Binding Types}"/><DataGridTextColumn Header="Message" Width="auto" Binding="{Binding Messages}"/><DataGridTextColumn Header="Critical" Width="auto" Binding="{Binding Critical}"/></DataGrid.Columns></DataGrid></Grid></Window>


My Model class SystemStatus.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace MVVM_DemoAppl.Models
{
    public class SystemStatus: INotifyPropertyChanged
    {
        public SystemStatus()
        {
 
        }
        private string _system;
        private DateTime _date;
        private string _type;
        private string _message;
        private bool _critical;

        public string Systems
        {
            get { return _system; }
            set { _system= value; OnPropertyChanged("_system"); }
        }

        public DateTime Date
        {
            get { return _date; }
            set { _date = value; OnPropertyChanged("Date"); }
        }
        public string Types
        {
            get { return _type; }
            set { _type = value; OnPropertyChanged("Types"); }
        }
        public string Messages
        {
            get { return _message; }
            set { _message = value; OnPropertyChanged("Messages"); }
         }
        public bool Critical
        {
            get { return _critical; }
            set { _critical = value; OnPropertyChanged("Critical"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

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

        
    }
}


My ViewModel class 

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Data.EntityModel;
using MVVM_DemoAppl.Models;
using MVVM_DemoAppl;


namespace MVVM_DemoAppl.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
      Model _myModel = new Model();
      private ObservableCollection<SystemStatus> _systemStatusData= new ObservableCollection<SystemStatus>();
      public ObservableCollection<SystemStatus> SystemStatusData
      {
        get { return _systemStatusData; }
        set
          {
            _systemStatusData= value;
            OnPropertyChanged("SystemStatusData");
          }
      }

    public MainViewModel()
     {
       initializeload();
     }

    private void initializeload()
    {
       DataTable table = _myModel.getData();

       for (int i = 0; i < table.Rows.Count; ++i)
       SystemStatusData.Add(new SystemStatus
       {
    Systems= table.Rows[i][0].ToString(),
    Date =Convert.ToDateTime(table.Rows[i][1]),
    Types = table.Rows[i][2].ToString(),
   Messages = table.Rows[i][3].ToString()             Critical = Convert.ToBoolean(table.Rows[i][1]),
        });
    }
   public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged(string propertyname)
    {
      var handler = PropertyChanged;
      if (handler != null)
      handler(this, new PropertyChangedEventArgs(propertyname));
    }
   }

  public class Model
   {
    string con = ConfigurationManager.AppSettings["ConnectionStrings"];
   public DataTable getData()
  {
   DataTable ndt = new DataTable();
   SqlConnection sqlcon = new SqlConnection(con);
   sqlcon.Open();
  SqlDataAdapter da = new SqlDataAdapter("select top 5 System,Date,Typ,Message,Critical from test_DB.dbo.SystemStatus",con);
  da.Fill(ndt);
  return ndt;
  }
 }
}

My MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


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


App.xaml.cs :

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using MVVM_DemoAppl.ViewModels;
using MVVM_DemoAppl.Views;

namespace MVVM_DemoAppl
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var mainWindow = new MainWindow();
            var viewModel = new MainViewModel();
            mainWindow.Show();
        }
    }
}

I have error in the following content of my MainWindow.xaml  as

"Cannot create an instance of "MainViewModel".

H:\MVVM_DemoAppl\MVVM_DemoAppl\MainWindow.xaml"

I tired replacing Datacontext in Xaml by ItemsSource for the Datagrid, but still I am having this error being raised. 

kindly help me to overcome this problem. Thanks indeed.






CellStyle BasedOn default CellStyle

$
0
0

I made a custom control called CustomDataGrid that inherits from DataGrid, and I put it in a DLL. Overriding the metadata I set for this control a new default style, different from the standard DataGrid one: this style include a custom CellStyle.

<Style TargetType="{x:Type prj:CustomDataGrid}">
...
        <Setter Property="CellStyle" Value="{StaticResource RightAlignCell}" />
...
</Style>

I use this DLL in a WPF project and I need to modify the CellStyle, but I can not reach the {StaticResource RightAlignCell} resource (located in the DLL) from the application. In other words I need to do something like:

<Custom:CustomDataGrid>
    <Custom:CustomDataGrid.CellStyle>
        <Style BasedOn="{StaticResource RightAlignCell}">
            <Setter Property="SomeProperty" Value="SomeValue"/>
        </Style>
    </Custom:CustomDataGrid.CellStyle>
</Custom:CustomDataGrid>

How can I perform it?
Thanks in advance

Viewing all 18858 articles
Browse latest View live


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