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

Rendered Rectangles missing in a huge WPF Control

$
0
0

Guys

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


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


I am using the following code to render in the DC.

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

WPF- Binding checkboxes

$
0
0

HI ,

I'm completely a beginner in WPF.I'm trying out few things with checkbox binding .however i got stuck here as i explained below.Someone please help me out on this.

I have created a Genericcontrol, where the required controls[custom code] are added in xaml.cs file [labels , checkboxes].loaded the  label context and checkboxes[display names] context from a ViewModel, also set the checkbox binding properties[to the corresponding view model] and tied the checkbox to a checked event in that .

Now whenever i am checking the checkbox , all the checkboxes i have loaded are getting selected.

I dont know how to handle this .Please help me out .Thank you .

CheckBoxColumn

$
0
0

I have DataGrid whith DataGridCheckBoxColumn 

<DataGrid >
                        <DataGrid.Columns>                           
                            <DataGridCheckBoxColumn Header="Статус"
                                                Binding="{Binding IsDone}"                                               
                                                />

HOW I can  VerticalAlignment="Center" for every one CheckBox in DataGridCheckBoxColumn 

MEF and Prism6

$
0
0

First of all is there a better forum for this question?
I am trying to understand Prism and MEF and can make it work with a single module in a directory.
The modules are very simple, just putting a message into a region.  They are all of type IFunction and are decorated with:-  
    [ModuleExport(typeof(IFunction))]
    [ExportMetadata("data","ABC")]
    public class ModuleAModule : IModule, IFunction
    {......
where Ifunction is an interface with just an Initialize method
What I am trying to do is get the modules into the IEnumerable 'functions' so I can get at them (eg to make a menu) but whatever I do 'functions' stays null although the module are put in the catalogue.
One message I get, which does not cause an design or run time error, is:
error CS1503: Argument 1: cannot convert from 'System.ComponentModel.Composition.Primitives.ComposablePartCatalog' to 'System.ComponentModel.Composition.Hosting.DirectoryCatalog'
With MEF Bootstrapper doing so much I find it very difficult to work out what is going on and debug.
The code below was drawn from reading a lot of tutorials.  Some were pretty old and that might be part of my difficulty, Prism and MEF are still changing pretty fast.
Can anyone point me in the right direction, or to an up-to-date sample or tutorial.

    public class Bootstrapper : MefBootstrapper
    {
        [ImportMany(typeof(IFunction))]
        public IEnumerable<Lazy<IFunction, IFunctionData>> functions { get; set; }
        protected override DependencyObject CreateShell()
        {
            return Container.GetExportedValue<MainWindow>();
        }
        protected override void InitializeShell()
        {
            Application.Current.MainWindow.Show();
        }
        protected override void ConfigureAggregateCatalog()
        {
            base.ConfigureAggregateCatalog();
            AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
            string dir = General.ModuleDirectory;  // from elsewhere in the program
            DirectoryCatalog catalog = new DirectoryCatalog(dir);
            AggregateCatalog.Catalogs.Add(catalog);
        }
        protected override void ConfigureViewModelLocator()
        {
            base.ConfigureViewModelLocator();
            ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(viewType =>
            {
                var viewName = viewType.FullName;
                viewName = viewName.Replace(".Views.", ".ViewModels.");
                var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
                var suffix = viewName.EndsWith("View") ? "Model" : "ViewModel";
                var viewModelName = String.Format(CultureInfo.InvariantCulture, "{0}{1}", viewName, suffix);
                var assembly = viewType.GetTypeInfo().Assembly;
                var type = assembly.GetType(viewModelName, true);
                return type;
            });
        }
    }


John Meers

Add tree view item dynamically in WPF

$
0
0

I have two user controls like name usercontrol1 and usercontrol2  in usercontrol1 i have one tree view.

In another usercontrol2 i have textbox and save button. on click of save button i need to add this value of textbox to the tree view item of usercontrol1.

usercontrol2.xaml

<WrapPanel Grid.Column="0" Name="wrapPanelSecurtiyGroup" Width="700" Height="auto" VerticalAlignment="Top"HorizontalAlignment="Right">
                <Label  Name="lblName" Content="Name" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="481"Margin="5,0,0,0" />
                <TextBox x:Name="txtName" VerticalContentAlignment="Center" Background="White" TextWrapping="NoWrap"Text="{Binding Name }" Margin="5,0,0,0" Width="611" Height="23"  >
                </TextBox>

<Button Name="btnSave" Content="Save" Click="Save_Click" Height="25" Width="100" Margin="120,0,0,0" />

</WrapPanel>

usercontrol2.xaml

<TreeView x:Name="controlTreeviewG" Background="{x:Null}" Margin="0,0,0,0" BorderBrush="{x:Null}">
                                    <TreeViewItem Header="GN" Tag="GN" FontSize="13"Name="treeGViewItem" ItemsSource="{Binding NItem}" >
                                    </TreeViewItem>
 </TreeView>

Code of usercontrol2.cs

                             

public partial class usercontrol2 : UserControl
    {
        private usercontrol1 _usercontrol1;

        public usercontrol2()
        {
            InitializeComponent();

        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
              //CLearing  children of wrapPanelAP

                //Setting Default Options
                _usercontrol1.treeGViewItem.Items.Add(txtName.Text.ToString());
                _usercontrol1.controlTreeviewG.Items.Refresh();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _usercontrol1= new usercontrol1 ();
        }

    }

this is what i  am doing but its not working, please suggest something that can be helpful to me


MinHeight for a grid item.

$
0
0
Hello. I have two grid rows and I want the first one to resize automatically until it goes over the MinHeight the second one. Unfortunately MinHeight of a second row definition doesn't work as I expect. I've found following link wpf-grid-sizing but I'm wondering if it's possible to come up with a better solution without a converter.

Number of row

$
0
0

I have Some class

        

 public class Enterprise
    {
        public int EnterpriseID { get; set; }

        public string Title { get; set; }

}

I conect List of this class to DataGrid.ItemSourse=List<Enterprise>

In DataGrid I have 2 columns

var dc0 = new DataGridTextColumn() { Header = "№/№", Width = 50, IsReadOnly = true,Binding = new Binding(?????????) };
var dc1 = new DataGridTextColumn() { Header = "Title", Binding = new Binding("Title "), Width = DataGridLength.Auto,      IsReadOnly = true };

I wont see number Row like

1 | BMW

2 | Opel

3 | Mersedes

But firs colunm NOT Id . Mast be number Row

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

$
0
0

the table should be able to:

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

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

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

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

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

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

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




Unable to add MahApps.Metro Controls in Visual Studio 2015 Toolbox

$
0
0

Hi,

       I have installed MahApps.Metro framework via NuGet UI. When I tried to add MahApps.Metro Controls to Toolbox, I got the following error message. Please help me to fix it. 


Thanks in advance for your help...

Regards,

Dhanisha



How to bind dynamic data to a WPF datagrid inside Row Details Template?

$
0
0
I have a datagrid,lets call it OuterGrid, that is populated with a List<object1> (Dynamically through code behind). Inside the row details template for OuterGrid, i want to add a datagrid, lets calls it InnerGrid, the InnerGrid needs to dynamically poupulated with List<object2> on the SelectionChange event of OuterGrid? Accessing the InnerGrid and binding it to a datasource needs to be done in the code behind. Can somone help me out with this? Its Urgent.

Xaml for the OuterGrid looks like:

 

 

<Grid>

 

 

<Grid.ColumnDefinitions>

 

 

</Grid.ColumnDefinitions>

 

 

<Grid.RowDefinitions>

 

 

</Grid.RowDefinitions>

<toolkit:DataGrid Grid.Row="0" Grid.Column="0" Name="OuterGrid" AutoGenerateColumns="False">

 

 

<toolkit:DataGrid.RowDetailsTemplate>

 

 

<DataTemplate>

 

 

<toolkit:DataGrid Name="InnerGrid" >

 

 

<toolkit:DataGrid.Columns>

 

 

<toolkit:DataGridTextColumn Header="Name" Binding="{Binding Name}"></toolkit:DataGridTextColumn>

 

 

 

</toolkit:DataGrid.Columns>

 

 

</toolkit:DataGrid>

 

 

</DataTemplate>

 

 

</toolkit:DataGrid.RowDetailsTemplate>


dependency properites vs attached properties?

$
0
0

HI...

I want to know the difference between dependency properties and attached properties.

Where should i use both and in which contract?

i want to see the difference from code as well as XAML  with output.

 

 

 


maifs

How to create popup user control WPF datagrid

$
0
0
XML<Popup Margin="0,0,0,0" Name="Popup1" PopupAnimation="Slide"           PlacementTarget="{Binding ElementName=Dgv}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="250" Height="150" />


       private void Dgv_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
 	            Point newPosition = new Point();
                double rowX = 0;
                DataGrid dg = GetRowsDataGrid(e.Row);
                if (dg != null)
                {
                    rowX = GetColumnXPosition(e.Column, dg);
                    newPosition = e.Row.TranslatePoint(new Point(Dgv.RowHeaderWidth, e.Row.ActualHeight), this);
                }

                if (newPosition != new Point())
                {
                    Popup1.PlacementRectangle = new Rect(rowX + Dgv.RowHeaderActualWidth, newPosition.Y - Dgv.Margin.Top, 0, 0);
                }
                Popup1.IsOpen = true;
        }

        private double GetColumnXPosition(DataGridColumn column, DataGrid grid)
        {
            double result = 0.0;
            if (grid == null)
                return result;
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                DataGridColumn dgc = grid.Columns[i];
                if (dgc.Equals(column))
                    break;
                result += dgc.ActualWidth;
            }
            return result;
        }

        private DataGrid GetRowsDataGrid(DataGridRow row)
        {
            DependencyObject result = VisualTreeHelper.GetParent(row);
            while (result != null && !(result is DataGrid))
            {
                result = VisualTreeHelper.GetParent(result);
            }
            return result as DataGrid;
        }
        private void Dgv_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            Popup1.IsOpen = false;
        }

I want to convert this to user controlusing below code
XAML

<DataGrid x:Class="WpfGrid.WGrid"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfGrid"
             mc:Ignorable="d"
             d:DesignHeight="300" Width="500" PreviewKeyDown="DataGrid_PreviewKeyDown" BeginningEdit="DataGrid_BeginningEdit" SelectionMode="Single" SelectionUnit="Cell" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserResizeRows="False" CanUserSortColumns="False" CanUserResizeColumns="False" EnableRowVirtualization="False" PreviewTextInput="DataGrid_PreviewTextInput"><DataGrid.Resources ><Popup x:Key="GPopup" Margin="0,0,0,0" Name="XPopup" PopupAnimation="Slide"  PlacementTarget="{Binding ElementName=WGrid}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="250" Height="150" /></DataGrid.Resources></DataGrid>

In code

          private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            Point newPosition = new Point();
                double rowX = 0;
                DataGrid dg = GetRowsDataGrid(e.Row);
                if (dg != null)
                {
                    rowX = GetColumnXPosition(e.Column, dg);
                    newPosition = e.Row.TranslatePoint(new Point(Dgv.RowHeaderWidth, e.Row.ActualHeight), this);
                }

                if (newPosition != new Point())
                {
                   **//Upto this it is ok  here I want to access the   <DataGrid.Resources > Gpopup and show it.**
                    Popup1.PlacementRectangle = new Rect(rowX + Dgv.RowHeaderActualWidth, newPosition.Y - Dgv.Margin.Top, 0, 0);
                }
                Popup1.IsOpen = true;


        }
I don't know I am right as I am new to Wpf so please help how to acheive this or is there any alternate to create user control
to popup window below a cell.

Thanks


programmer

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

$
0
0

Hello.

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

*** .NET Runtime Error ***

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


*** Application Error ***

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



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


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


Disable/Hide RibbonButton

$
0
0

Hi,

I have a WPF MAsk with a Menue

</RibbonGroup><RibbonGroup Header="Drucken Vorbereitung"><!-- <Ribbon:RibbonMenuButton Label="Wahlvorbereitung" Name="RIMBDRV"  LargeImageSource="C:\WVIS-WPF\Bmp\Unbenannt2.png"> --><RibbonMenuButton Label="Wahlvorbereitung" Name="RIMBDRV"><RibbonMenuButton.Items><RibbonButton Label="Wahlkreise"                Name="RIBTDRVWKRS" HorizontalAlignment="Left" Click="RIBTDRVWKRS_Click" Focusable="False" IsEnabled="False" IsHitTestVisible="False" PreviewMouseMove="RIBTDRVWKRS_PreviewMouseMove" /><RibbonButton Label="Wohnbezirke"               Name="RIBTDRVWOBZ" HorizontalAlignment="Left" /><RibbonButton Label="Wahlbezirke"               Name="RIBTDRVWBEZ" HorizontalAlignment="Left" /><RibbonButton Label="Wahlbezirksschilder"       Name="RIBTDRVWBEZS" HorizontalAlignment="Left"/><RibbonButton Label="Parteien"                  Name="RIBTDRVPAR"  HorizontalAlignment="Left"/><RibbonButton Label="Bewerber"                  Name="RIBTDRVBEW"  HorizontalAlignment="Left"/><RibbonButton Label="Öffentliche Bekanntmachung" Name="RIBTDRVOEBEK" HorizontalAlignment="Left" Click="RIBTDRVOEBEK_Click"/><RibbonButton Label="Stimmzettel"               Name="RIBTDRVSTZ"  HorizontalAlignment="Left"/><RibbonButton Label="Blanko Zählliste"          Name="RIBTDRVBZL"  HorizontalAlignment="Left"/><RibbonButton Label="Blankoschnellmeldung"      Name="RIBTDRVBLSM" HorizontalAlignment="Left"/><RibbonButton Label="Vollständigkeitskontrolle" Name="RIBTDRVVSK"  HorizontalAlignment="Left"/></RibbonMenuButton.Items></RibbonMenuButton></RibbonGroup>

How can i Disable/Hide the "RIBTDRVWKRS" Button so that nowbody can click on this Button.

Have anyone an idea?

IsEnable=false; / Focusable=fasle; is not enought... (I can klick on the Button)...

Best Regards

Bernd

TextBox's Tooltip cannot display Error information.

$
0
0

Hi All,

I created a WPF application, the Model like below,

    class Customer : INotifyPropertyChanged, IDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _name;

        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                if (_name != value)
                {
                    _name = value;

                    OnPropertyChanged("Name");
                }
            }
        }        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                string errorInfo = "";

                if(columnName == "Name")
                {
                    if(string.IsNullOrWhiteSpace(Name))
                    {
                        errorInfo =  "Name cannot be null or empty.";
                    }
                    else
                    {
                        errorInfo = null;
                    }
                }

                return errorInfo;
            }
        }

        public Customer(string customerName)
        {
            _name = customerName;
        }
    }

ViewModel

    class CustomerViewModel
    {
        private Customer _customer;        public Customer Customer
        {
            get
            {
                return _customer;
            }
        }

        public ICommand UpdateCommand { get; private set; }

        private CustomerInfoViewModel _childViewModel;

        public CustomerViewModel()
        {
            _customer = new Customer("TOM");

            _childViewModel = new CustomerInfoViewModel();

            UpdateCommand = new CustomerUpdateCommand(this);
        }

        public void SaveChanges()
        {
            CustomerInfoView childView = new CustomerInfoView();

            childView.DataContext = _childViewModel;

            _childViewModel.Info = string.Format("{0} was update.",_customer.Name);

            childView.ShowDialog();
        }
    }

In the View,

<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="0,5"><TextBlock Text="Customer Name:" /><TextBox
            Text="{Binding Customer.Name,
            UpdateSourceTrigger=PropertyChanged,
            ValidatesOnDataErrors=True}"
            Width="150"
            Margin="10,0"ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem.ErrorConent}"VerticalContentAlignment="Center"></TextBox><Button Content="Update"
                Command="{Binding UpdateCommand}" /></StackPanel>

I want to binding the error information to TextBox's tooltip property. But when the error occurred. The error information didn't display. How to fix this issue? and Why?

Thanks,


How to bind an UserControl to a subviewmodel property?

$
0
0

Dear community,

right now I'm trying to bind to a usercontrol. My main window's datacontext is set to the MainViewModel and the GUI has a UserControl. The main ViewModel holds two subviewmodels. I would like to bind a string property of a subviewmodel to a label in the UserControl. Binding should insure that the displayed label changes, when the sub-ViewModel property changes.

In my example I can set the usercontrol property directly in the xaml-code of the MainWindow.xaml. Binding to the "SubViewModel1.LabeText" is not possible.

I would be glad and thankfull if you could give me some directions, because this problem really holds back my further development and this problem I can not solve alone by searching stackoverflow.

You can find the simplified code below.

Best regards,

Apfelman


MainViewModel.c

namespace UserControlBinding
{
    class MainViewModel
    {

        public SubViewModelBase SubViewModel1;
        public SubViewModelBase SubViewModel2;

        public MainViewModel(SubViewModelBase SubVM1, SubViewModelBase SubVM2)
        {
            SubViewModel1 = SubVM1;
            SubViewModel2 = SubVM2;
        }
    }
}

MainWindow.xaml

<Window x:Class="UserControlBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:UserControlBinding"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="120"><Window.DataContext><local:MainWindow/></Window.DataContext><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="5" /><ColumnDefinition Width="50" /><ColumnDefinition Width="50" /><ColumnDefinition Width="5" /></Grid.ColumnDefinitions><local:UserControl1 Content="{Binding <!--SubViewModel1.LabelText? how do I bind to SubviewModel1.LabelText?-->}" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Center"></local:UserControl1></Grid></Window>

MainWindow.xaml.cs

namespace UserControlBinding
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SubViewModel1 SubVM1 = new SubViewModel1("SVM1");
            SubViewModel1 SubVM2 = new SubViewModel1("SVM2");

            this.DataContext = new MainViewModel(SubVM1, SubVM2);
        }
    }
}
SubViewModelBase.cs
using System;
using System.ComponentModel;

namespace UserControlBinding
{
    class SubViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        readonly String Identifier = "Default";

        private String _LabelText = "DefaultText";

        public String LabelText
        {
            get { return _LabelText; }
            set
            {
                OnPropertyChanged("LabelText");
                _LabelText = value;
            }
        }

        public SubViewModelBase(String ID)
        {
            Identifier = ID;
        }

        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

SubViewModel1.cs

using System;

namespace UserControlBinding
{
    class SubViewModel1 : SubViewModelBase
    {
        public SubViewModel1(String ID):base(ID)
        {
        }

    }
}

UserControl1.xaml

<UserControl x:Class="UserControlBinding.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"
             xmlns:local="clr-namespace:UserControlBinding"
             mc:Ignorable="d"
             d:DesignHeight="40" d:DesignWidth="40"
             Name="TextDisplay"><Grid><Label x:Name="lbl_Text" Content="{Binding Path=DisplayLabel, ElementName=TextDisplay}"></Label></Grid></UserControl>

UserControl1.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;


namespace UserControlBinding
{
    /// <summary>
    /// Interaktionslogik für UserControl1.xaml
    /// </summary>
    public partial class UserControl1 : UserControl
    {

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

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


        public UserControl1()
        {
            InitializeComponent();
        }
    }
}



How to display persian date to datetimepicker in c#

$
0
0
I am developing C#.net desktp application .I want to put datetimepicker on the form to select persian date,so default is miladi .how can I change It to shamsi date

Coverting from WinForm - Runtime error - 'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll Parameter count mismatch

$
0
0

This is an odd issue. When working on this yesterday, the program would stop, highlight the area of code I was working on and present "NullReferenceException," and linked to this page.

NullReferenceException Class

TODAY, without changes I am getting the error in the title. 

I am learning c#, and found an application in an area I have need to learn.

After coming along fine, and using this example on learning more, I ran into issues with limitations in Windows Forms, thus started the change to WPF.

The original code I am working with can be found here:

Paste Bine: PCCom.SerialCommunication Version 1.0.0.0

You can download the entire original project, if you wish, at

www.dreamincode.net - Serial Cmmunications Project

Here is the section of code presenting the error. The error occurs when "return true;" is executed.

 #region OpenPort
        public bool OpenPort()
        {
            try
            {
                //first check if the port is already open
                //if its open then close it
                if (comPort.IsOpen == true) comPort.Close();
                //set the properties of our SerialPort Object
                comPort.BaudRate = int.Parse(_baudRate);    //BaudRate
                comPort.DataBits = int.Parse(_dataBits);    //DataBits
                comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _stopBits);    //StopBits
                comPort.Parity = (Parity)Enum.Parse(typeof(Parity), _parity);    //Parity
                comPort.PortName = _portName;   //PortName
                //now open the port
                comPort.Open();
              
                return true;
            }
            catch (Exception ex)
            {
                DisplayData(ex.Message);
                return false;
            }
        }
        #endregion

I have no idea on what is going on with this. Some helpful explanations would be great.

The error I was having yesterday, was in another section of the program:

What I am currently working on is:

private RichTextBox _displayWindow;

I have since changed to:

private TextBox _displayWindow;

And the code I have been working on to convert to wpf which generated the NullReferenceException

 private void DisplayData(string msg)
        {
            _displayWindow.Dispatcher.Invoke(new EventHandler(delegate
            {
                _displayWindow.SelectedText = string.Empty;
                _displayWindow.AppendText(msg);
                _displayStatus.ScrollToLine(_displayStatus.GetLineIndexFromCharacterIndex(_displayStatus.SelectionSta‌​rt));
                //_displayWindow.ScrollToCaret();
               
            }));
        }

Thanks

Streaming video from server in WPF

$
0
0

Hi All,

Media Element only downloads the file and then allows the user to play. Is there any way in WPF to stream directly from the server ? Kindly Advise.

Thanks,

Loga


Data From Server

$
0
0
There are sites where you connect the data are updated automatically, eg currency rates. How can I catch with the help of C # data that the server sends to me.
Viewing all 18858 articles
Browse latest View live