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

PropertChanged Event is not getting triggered to change the property of a control in WPF UserControl @Runtime.

$
0
0

Hi,

I want to Enable a button based on somecondition in runtime so i am trying with PropertyChanged event as shown in below code and itseems not to work.

MyUIPage.xaml

<UserControl x:Class="MyNameSpace.MyUIPage"
             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:ModelSpace="clr-namespace:MyNameSpace.Models"
             mc:Ignorable="d" d:DesignHeight="600" d:DesignWidth="300" FontFamily="Segoe UI" Background="White">

<Button x:Name="MyButton" IsEnabled="{Binding ModelSpace.MyModel.IsMyButtonEnabled,Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" RenderOptions.BitmapScalingMode="HighQuality"   Style="{DynamicResource MyButtonStyle}" />

I have this code in my model class

namespace MyNameSpace.Models
{
    class MyModel : INotifyPropertyChanged
    {

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

        private bool _isMyButtonEnabled = false;
        public bool IsMyButtonEnabled
        {
            get
            {
                return _isMyButtonEnabled;
            }
            set
            {
                _isMyButtonEnabled = value;
                OnPropertyChanged("IsMyButtonEnabled");
            }
        }

 public PrecedentDetailsModel()
        {
  //I set the default value
  IsMyButtonEnabled = true;
 }

public void ChangePropertyStyle()
 {

  //Based on some condition, I change the property here
  IsMyButtonEnabled = false;
 }

    }
}

Please let me know if i am missing anything in the code, Am i doing the binding correctly or not ? I am calling ChangePropertyStyle() method on a Button Click event.

Regards,


Chetan Rajakumar


ToolBar width Height changes when ToolTray Orientation changes

$
0
0

HI 

I have created a form which contains tooltray containing N number for toolbar when i change the Band of any toolbar after that when i  change orientation the entire band which i have changed containing toolbar width increased.

Thanks in advance


##Goals are not necessary to motivate us.They are essential to really keep us alive.##

It's time for the TechNet Wiki WPF "Great Guru Love-in"! You too can get some loving!

$
0
0

February at TechNet Wiki usually involves a lot of love...

 

We love to read.

We love to learn.

We love our gurus, for they love to give.

 

Computer Geek Love Story Stock Photos

 

We love to make friends and promote great content.

We love to meet the community, and get closer to you.

  

 

We love to interview our winners, and bestow much love and honor upon them.

We love to tell the world of your achievements, and we promote those most active to inner circles!

All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something you had to solve for your own day's work today.

Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!

This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations toTechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you've contributed)

3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favoured technology will help us learn the active members in each community.

Feel free to ask any questions below.

More about TechNet Guru Awards

Thanks in advance!
Pete Laker


#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!



#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!

How to use IComponentConnector

$
0
0

Hi all,

I want to make an UserControl that  inheritting from IComponentConnector, but it always has an error when calling the method of the 'InitializeComponent'.

It says that have an conflict between UserControl.InitializeComponent an UserControl.InitializeComponent.

Why?

TPL and Main thread objects

$
0
0

Hi,

if my app.cs i am using this code to do some initialization stuffs

    public void Setup()
        {
         //ORM Setup
         // SomeSTuffs
         CardioRC1.MainWindow mw = ((CardioRC1.MainWindow)this.MainWindow);
}



protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();
            Task.Factory.StartNew(Setup).ContinueWith(
               (t) =>
               {
                  finalstuffs()
               }, UISyncContext);
        }


i have an exception at line

   CardioRC1.MainWindow mw = ((CardioRC1.MainWindow)this.MainWindow);

saying that you can not access main thread objects ... etc

The calling thread cannot access this object because a different thread owns it.

so what's going on , and how to fix that please ?

[WPF] ComboBox and ItemSource: add one empty row

$
0
0

Hi,

I have a ComboBox, defined as:

<ComboBox Name="cmbTypeOfSchedule"
		DataContext="{StaticResource DomainDataViewModel}"
		ItemsSource="{Binding SchedTypes}"
		DisplayMemberPath="Description"
		Width="120">


I would insert, in head, an empty item or empty called "Select all".

So:

1) I defined a StaticResource:

<CollectionViewSource x:Key="SchedTypesWithEmptyItem" Source="{Binding SchedTypes}" />

2) Edit my Combobox as:

<ComboBox Name="cmbTypeOfSchedule"
                                        DataContext="{StaticResource DomainDataViewModel}"
                                        DisplayMemberPath="Description"
                                        Width="120"><ComboBox.ItemsSource><CompositeCollection><ComboBoxItem Content="Select all" /><CollectionContainer Collection="{Binding Source={StaticResource SchedTypesWithEmptyItem}}" /></CompositeCollection></ComboBox.ItemsSource>

The problem: in the ComboBox I see only "Select all" and not other item from my Collection and when I select "Select all", it does not stay selected.

Thanks.

[MVVM pattern, WPF] Bind Usercontrols to a TabControl

$
0
0

Hi,

I am trying to add usercontrols to a tabcontrol in a viewmodel. In the mainwindow viewModel I have a ObservableCollection<ViewModelBase> TabItems with a collection of viewmodels from usercontrols, 
and bind these to the tabcontrol in mainwindow.xaml
Now, when I click on a other tab, the viewmodel changes, but the view content stays the same.
This is not strange because I bind the content to <vw:UserControlGmcMain> (the first usercontrol)
I don't want to do this and not include all usercontroll in the xaml-file, but only in the viewmodel.
I am searched for days now but can't find a good solution for this.
How do I achieve this?

Here is what I have done:

MainWindow.xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:TheNewEcMaintenanceSuite.ViewModel" xmlns:vw="clr-namespace:TheNewEcMaintenanceSuite.View" xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation" x:Class="TheNewEcMaintenanceSuite.ViewModel.MainWindow" WindowStartupLocation="CenterScreen" Title="MainWindow" Height="477.612" Width="480.597" Background="White" DataContext="{DynamicResource ViewModelMain}"><Window.Resources><vm:ViewModelMain x:Key="ViewModelMain"/></Window.Resources><Stackpanel>

<TabControl ItemsSource="{Binding TabItems}" SelectedItem="{Binding SelectedTab}"><TabControl.ItemTemplate><!-- this is the header template--><DataTemplate><TextBlock Text="{Binding TabName}" /></DataTemplate></TabControl.ItemTemplate><TabControl.ContentTemplate><!-- this is the body of the TabItem template--><DataTemplate><vw:UserControlGmcMain /><!--<ContentControl Content="{Binding Path=TabItems}"/>--></DataTemplate></TabControl.ContentTemplate></Stackpanel></Grid></Window>

ViewModelMain.cs:

using System;
using System.Collections.ObjectModel;
using TheNewEcMaintenanceSuite.ViewModel.Helpers;

namespace TheNewEcMaintenanceSuite.ViewModel
{
  class ViewModelMain : ViewModelBase
  {
    #region Private properties
    private ObservableCollection<ViewModelBase> _tabItems = new ObservableCollection<ViewModelBase>();
    private int _selectedTab = 0;
    #endregion

    /// <summary>
    /// Contructor
    /// </summary>
    public ViewModelMain()
    {
      //fill tab collection with views
      TabItems.Add(new ViewModelUserControlGmcMain("GMC"));
      TabItems.Add(new ViewModelUserControlScuMain("SCU"));
    }

    #region Public properties
    public ObservableCollection<ViewModelBase> TabItems
    {
      get
      {
        return _tabItems;
      }
      private set
      {
        _tabItems = value;
        OnPropertyChanged("TabItems");
      }
    }

    public int SelectedTab
    {
      get { return _selectedTab; }
      set
      {
        if (value != _selectedTab)
        {
          _selectedTab = value;
          OnPropertyChanged("SelectedTab");
        }
      }
    }
    #endregion
  }
}

Source code

Who can help me?


CustomControl: Can't access xaml style from codebehind before initializing object

$
0
0

hey

in my customcontrol there are some DependencyProperties which access elements from the generic.xaml file in the following way:

rectangle = this.GetTemplateChild("BackgroundRectangle") as Rectangle;
Now, if i put my control into a other Project, i can not access these dependencyproperties, without an "null reference" exception is thrown. Means, how Long the Control isn't initialized, the custom control cannot access the gerneric.xaml file.

Wgere is my mistake?


How to add a dynamic drop down list in RDLC reports in WPF

$
0
0

I have to Load an RDLC report in WPF application and need to include a drop down list in report.Based on the selection of drop down list different reports to be generated.I am using C# and WPF.

Eg: I have to list the details of employees in in RDLC report.There is a country drop down list, Based on the selection of country drop down list we need to display details of employees in the selected country.

Collapse a column of a grid and controls contained

$
0
0

Hello,

I have a grid in a similar situations :

<Grid Margin="0,0,0,0" Grid.Row="1" Height="Auto"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="0.33*"/><ColumnDefinition Width="0.33*"/><ColumnDefinition Width="0.33*"/><ColumnDefinition Width="0.33*" x:Name="ColumnToCollapse"/></Grid.ColumnDefinitions>

from code i set to visibility.collapse the column if a condition is verified, but in my grid i have a blank space where before there is that column. How i can permit to the grid to extends over the collapsed column?

Many thanks :)


www.Photoballot.net

Notify changes between windows

$
0
0

In my MainWindow, I have a listview whose SelectedItem is bound to a viewmodel.

When I click on the Edit menu item in the MainWindow, a separate window acting as a custom dialog allows me to edit that item.

However, how do I get the SelectedItem in my MainWindow to reflect the changes made in the other window?


Collins

Can Unity game file be embedded in WPF Application using C# Visual Studio2012?

$
0
0
Can Unity game file be embedded in WPF Application using C# Visual Studio? I need to embed unity 3D application in WPF using C# in visual studio.

RichTextBox Binding to a String or something else

$
0
0

Hello.

First, I'am from Germany and I have to learn english and this is the reason, why I wrote my question in english.

My problem is: I want to bind a RTF to a String or something else, to work with the informations in behind code.

But after I searched to get more informations about this, I got 2 codes which should help me to bind a FlowDocument to a RTf.

/*This simply takes the string and reads it line by line. If we have the desired characters at the end of a line (“:.”),
         * then we make the line blue and bold and remove the characters, otherwise we just add the text.
         * Each line is added as a paragraph so to reduce the space between each one.
         http://www.codeproject.com/Articles/137209/Binding-and-styling-text-to-a-RichTextBox-in-WPF*/
        protected Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
        {
            FlowDocument doc = new FlowDocument ();

            String s = value as String;

            if(s != null)
            {
                using ( StringReader reader = new StringReader ( s ) )
                {
                    String newLine;
                    while ( ( newLine = reader.ReadLine () ) != null )
                    {
                        Paragraph paragraph = null;
                        if ( newLine.EndsWith ( ":." ) == true )
                        {
                            paragraph = new Paragraph ( new Run ( newLine.Replace ( ":.", string.Empty ) ) );
                            paragraph.Foreground = new SolidColorBrush ( Colors.Blue );
                            paragraph.FontWeight = FontWeights.Bold;
                        }
                        else
                            paragraph = new Paragraph ( new Run ( newLine ) );

                        doc.Blocks.Add ( paragraph );
                    }
                }
            }

            return doc;
        }

public class BindableRichTextBox : RichTextBox
    {
        public static readonly DependencyProperty DocumentProperty = DependencyProperty.Register ( "Document", typeof ( FlowDocument ), typeof ( BindableRichTextBox ), new FrameworkPropertyMetadata ( null, new PropertyChangedCallback ( OnDocumentChanged ) ) );

        public new FlowDocument Document
        {
            get
            {
                return (FlowDocument) this.GetValue ( DocumentProperty );
            }
            set
            {
                this.SetValue ( DocumentProperty, value );
            }
        }

        public static void OnDocumentChanged ( DependencyObject obj, DependencyPropertyChangedEventArgs args )
        {
            RichTextBox rtb = (RichTextBox) obj;
            rtb.Document = (FlowDocument) args.NewValue;
        }

But know I have no idea, how to work with this code. 

Can maybe anyone help me?

Tom

WPF Change Opacity of Image Button when MouseEnter Ellipse

$
0
0

I have an ellipse on window that I would like to have it fade in/out a button when you over over the ellipse. Currently when you over over the button it fades in it out but I'd also like to have it do the same thing when you over over the image. Pretty new to WPF so this is what I have currently.  Any way to apply this existing fade when hovering over the ellipse too??

<Window.CommandBindings><CommandBinding Command="ApplicationCommands.Close"
            Executed="CloseCommandHandler"/></Window.CommandBindings><Window.Resources><Style x:Key="FadeOutButton" TargetType="{x:Type Button}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border Background="Transparent"><ContentPresenter/></Border></ControlTemplate></Setter.Value></Setter><Style.Triggers><EventTrigger RoutedEvent="Control.MouseEnter"><BeginStoryboard><Storyboard ><DoubleAnimation Duration="0:0:0.2" To="1" Storyboard.TargetProperty="Opacity"/></Storyboard></BeginStoryboard></EventTrigger><EventTrigger RoutedEvent="Control.MouseLeave"><BeginStoryboard><Storyboard ><DoubleAnimation Duration="0:0:0.2" To="0" Storyboard.TargetProperty="Opacity"/></Storyboard></BeginStoryboard></EventTrigger></Style.Triggers></Style></Window.Resources><Grid><Ellipse Fill="#FF2C2CB8" Cursor="Hand" Margin="0"
                 StrokeThickness="1" Width="50" Height="50" VerticalAlignment="Top" MaxWidth="50" MaxHeight="50" HorizontalAlignment="Center" MouseUp="Image_MouseUp" ><Ellipse.Effect><DropShadowEffect BlurRadius="10" Direction="270"/></Ellipse.Effect></Ellipse><TextBlock TextWrapping="WrapWithOverflow"
                   Margin="15,0,15,10" Foreground="White" FontWeight="Bold"
                   FontSize="14" TextAlignment="Center" Padding="0,5,0,0" MouseUp="Image_MouseUp" Cursor="Hand">
            My Docs</TextBlock><Button x:Name="bx" Style="{StaticResource FadeOutButton}" HorizontalAlignment="Left" VerticalAlignment="Top"
               Cursor="Arrow" Width="21" Height="21" Opacity="0"
                BorderThickness="0" Command="ApplicationCommands.Close"
                 MaxWidth="21" MaxHeight="21" Margin="52,0,0,0"
                HorizontalContentAlignment="Left"
                VerticalContentAlignment="Top" Padding="0"><StackPanel Orientation="Horizontal"><Image Source="WIP_X.png" Width="21" Height="21"/></StackPanel></Button></Grid>

Need some samples to make Entity framework interact with WPF

$
0
0

HI guys,

I need to create an app which will query all details about customer from very big database for different search crieria. I don't have any sp to call individual section details of customer. so i planned to go with Entity framework and WPF. Both are new to me.

Could someone please help me  with creating good WPF application (beautiful look and feel) & entity framework interaction with DB?

or any other to make this requirement in an easy way with latest technologies.. All i need some good UI for searching customer details..

thanks in advance

Regards

bala


Balamurugan


Undo & redo for gdi graphics

$
0
0

Im trying to implement undo and redo using gdi in wpf. I am not very familiar with gdi and my attempts have been unsuccessful.

On my mouse move event I draw like this:

   using (var g = Gdi.Graphics.FromImage(tempBitmap))
    {
        g.SmoothingMode = Gdi.Drawing2D.SmoothingMode.AntiAlias;
        g.CompositingQuality = Gdi.Drawing2D.CompositingQuality.HighQuality;
        if (currentTool == "eraserBrush")
            g.CompositingMode = Gdi.Drawing2D.CompositingMode.SourceCopy;
        else
            g.CompositingMode = Gdi.Drawing2D.CompositingMode.SourceOver;
        g.DrawLine(pen,p0,p1);
    }

    // Copy GDI bitmap to WPF bitmap.
    var hbmp = tempBitmap.GetHbitmap();
    var options = BitmapSizeOptions.FromEmptyOptions();
    this.writableBmp.Source = Imaging.CreateBitmapSourceFromHBitmap(hbmp,
        IntPtr.Zero, Int32Rect.Empty, options);

    // Redraw the WPF Image control.
    this.writableBmp.InvalidateMeasure();
    this.writableBmp.InvalidateVisual();

tempBitmap is a Gdi bitmap

On my mouse up event I push tempBitmap to a stack, and on my undo event I pop from the stack and do the following:

if (paintStack.Count <= 1)
                    return;

                paintStack.Pop();
                tempBitmap = paintStack.Peek();
 var hbmp = paintStack.Peek().GetHbitmap();
                var options = BitmapSizeOptions.FromEmptyOptions();
                this.writableBmp.Source = Imaging.CreateBitmapSourceFromHBitmap(hbmp,
                    IntPtr.Zero, Int32Rect.Empty, options);

                // Redraw the WPF Image control.
                this.writableBmp.InvalidateMeasure();
                this.writableBmp.InvalidateVisual();

But hitting undo does nothing. I believe I am pushing and poping the wrong item to the stack. I think I should be doing the gdi graphics, and not the tempbitmap, but I am not sure how.

WPF by C-Pad programming

$
0
0

C-Pad is what i intrepret as cmd and notepad programming.I have done VB.Net and C# with C-Pad successfully--given any complicated programme.Even with 250 textboxes,12 butons etc etc.

 I am trying the same with wpf.I am not geting a grip of it.Can any expert suggest a simple programme where in a simple wpf programme--say messagebox with "Hello,world" is achieved.I shall follow it up from there.I am getting difficulty in calling the compiler and also how to compile the xaml file with vb file.Thanks in advance.

   I am not a professional programmer.I am aged 68 and is interested in prgrammming as a hobby.

Thanks in advance.

Venkatraman

WPF issues

$
0
0

Can Microsoft WPF team make WPF more user/developer friendly?

Is it possible that WPF ListView has the capability to access column (grid) of the List? I mean accessing the column cell while the cell is clicked by mouse. It seems not able to do so at this moment.

Is it possible that whatever WPF control has the capability to allow developer to design the interface easier? for example, a developer can specify the elements of a control, then WPF can generate the codes and XAML for the developer? To be more epecific, can a developer design a ListView, and assign each column of the Listview attributes, then WPF generates the WAML and code behind for the ListView designed? Developer then can modify the code behind for additional functions. I think this can be done better. For simple text column, it's been done. But, for complex column such as image/picture objects, it's not done yet. Developer should be able to specify the (dynamic) data source for the image/picture column, then it's done. This is the area where Microsoft can improve and should have improved quite a bit.


C# Project needs Project!

$
0
0

Hi guys,

Im working on a big project and so i created a projectmap

Well I have now project A and project B

Project A: is a C# Consoleapplication

Project B: is a C# WPF Application

Well, B is the startproject. And now: how can i run Project A in project b? I need them.

Thanks in advance

WPF animation like windows 10 Notification Panel

$
0
0

Trying to mimic the smooth transition you get with the notification panel in windows 10 opening up in WPF and having trouble with it jittering as it moves. Also having trouble binding the final values e.g.

<EventTrigger RoutedEvent="Window.Loaded"><BeginStoryboard><Storyboard ><DoubleAnimation Duration="0:0:.8" Storyboard.TargetProperty="Left" From="{Binding PrimaryScreenRight}" To="{Binding PrimaryScreenRightMinusWidth}" AccelerationRatio=".1"/></Storyboard></BeginStoryboard></EventTrigger>

Any advice or simple example on how to achieve a similar animation resizing the form as is achieved via the notification panel?

I notice the shadow doesn't appear until after it has finished moving which makes me think a different method is been used to animate the form.
Viewing all 18858 articles
Browse latest View live


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