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

How do you access methods of user controls in a stack panel?

$
0
0

Hello Everyone,

Please forgive me, I am new to WPF and C# development.  However, I am sure this can be done based on what I have read.

I have a lot of custom user controls that basically manages CRUD operations, there is about 80 in all.

Based on the activity of the user, let say client data entry.  The client detail custom user control is loaded on the parent window inside a stack panel.  The client detail custom user control has CRUD methods (addRecord(), editRecord(), deleteRecord()).

I want the parent window to call the CRUD methods on the custom user controls when a user clicks on a button.  

For instance, on the parent window, when the user clicks the "Add Record" button, the addRecord() method on the custom user control is called.

And when I want the custom user control to call method that is on the parent, such as when the record is not saved and the user tries to close the window, I know how the keep the window from closing, however, sending the message to the parent window is tricky.

I tried several options and feel that I am close.  Thanks for any help that you can provide.

Thanks!


XML serialization List problem

$
0
0

Hey there,

I want to save custom classes to file, so I need to pass a serialization. Those classes are mostly of Canvas, Line stuff, so I need an XML Serialization.

I have a custom class:

class Kanvas
{
     Line l;
     Canvas c;
     double width;
     //... and so on
     public Kanvas()
     {
          c = new Canvas();
             // so on
     }
}

and I need to serialize a List<Kanvas> of those Kanvas objects.

Here's my serialization:

List<Kanvas> KK = new List<Kanvas>();

//filling KK with some Kanvas...

System.IO.FileStream filestream = new System.IO.FileStream("D:\\file.txt", System.IO.FileMode.Create);
XmlSerializer xm = new XmlSerializer(typeof(List<Kanvas>);
xm.Serialize(filestream, KK);
filestream.Close();

and I get an exception "There was an error reflecting type..." thrown. I did some searching and found that the problem is in line where XmlSerializer object is created. Maybe the typeof() ?

Please help!


Knowledge: C, C++, C#, Java, Pawn

Questions on the xaml for binding

$
0
0

Getting a refresh on mvvm and wpf after some years. I've got some questrions on the following xaml:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example with Navigation" Height="350" Width="525">

    <Window.Resources>
        <DataTemplate DataType="{x:Type local:HomeViewModel}">
            <local:HomeView />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ProductsViewModel}">
            <local:ProductsView />
        </DataTemplate>
    </Window.Resources>

    <DockPanel>
        <Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
            <ItemsControl ItemsSource="{Binding PageViewModels}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Name}"
                                Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                                CommandParameter="{Binding }"
                                Margin="2,5"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Border>

        <ContentControl Content="{Binding CurrentPageViewModel}" />
    </DockPanel>
</Window>

What is the relative source attribute? What is it providing? How does it work?

and the button command is bound to who? is it looking for a property called ChangePageCommand belonging to a PageViewModel object or belonging to the datacontext of the Window?

MDI form in WPF

$
0
0

I want to create a MDI Parent form and a Child form in WPF. When i drag my parent , child also should move with parent.

How to achieve this requirement?


WPF use Multi-thread question

$
0
0

I want save all UserControl as image, at the same time, I need to show a animation in order to make the UI better for users.

This is MainWindow:

<Window x:Class="WPF.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:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:local="clr-namespace:FluidV.Components"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:vw="http://inosoft.com/visiwin7"
         d:DesignHeight="100"
         d:DesignWidth="1024"
         mc:Ignorable="d"><Grid x:Name="LayoutRoot"><Button Margin="10" Click="Button1_click"/></Grid></Window>

This is UserControl:

<UserControl x:Class="WPF.AnimationView"
         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"
         Opacity="0.6"
         Background="#A8007499"
         mc:Ignorable="d"
         d:DesignHeight="300"
         d:DesignWidth="300"><Grid><DataGrid Name="dataGrid1"
                  Width="441"
                  Height="99"
                  Margin="40,70,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  AutoGenerateColumns="False" /><Canvas Name="loading"
                Width="120"
                Height="120"
                Margin="187,76,241,85"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                RenderTransformOrigin="0.5,0.5"><Ellipse Canvas.Left="55"
                     Canvas.Top="31"
                     Width="15"
                     Height="15"
                     Fill="#FFD1D1F7"
                     Opacity="1.0"
                     Stretch="Fill" /><Ellipse Canvas.Left="38"
                     Canvas.Top="39"
                     Width="15"
                     Height="15"
                     Fill="Blue"
                     Opacity="0.8"
                     Stretch="Fill" /><Ellipse Canvas.Left="36"
                     Canvas.Top="58"
                     Width="15"
                     Height="15"
                     Fill="#FF0000FE"
                     Opacity="0.7"
                     Stretch="Fill" /><Ellipse Canvas.Left="52"
                     Canvas.Top="67"
                     Width="15"
                     Height="15"
                     Fill="Blue"
                     Opacity="0.6"
                     Stretch="Fill" /><Ellipse Canvas.Left="68"
                     Canvas.Top="61"
                     Width="15"
                     Height="15"
                     Fill="#FF2E2EFF"
                     Opacity="0.5"
                     Stretch="Fill" /><Ellipse Canvas.Left="69"
                     Canvas.Top="42"
                     Width="15"
                     Height="15"
                     Fill="#FF6F6FFF"
                     Opacity="0.4"
                     Stretch="Fill" /><Canvas.RenderTransform><RotateTransform x:Name="SpinnerRotate"
                                 Angle="0" /></Canvas.RenderTransform><Canvas.Triggers><EventTrigger RoutedEvent="ContentControl.Loaded"><BeginStoryboard><Storyboard><DoubleAnimation Duration="0:0:0.8"
                                             From="0"
                                             RepeatBehavior="Forever"
                                             Storyboard.TargetName="SpinnerRotate"
                                             Storyboard.TargetProperty="(RotateTransform.Angle)"
                                             To="360" /></Storyboard></BeginStoryboard></EventTrigger></Canvas.Triggers></Canvas></Grid></UserControl>

This is MainWindow.xaml.cs:

 private void Button1_click(object sender, RoutedEventArgs e)
          {

              Thread t = new Thread(new ThreadStart(() => { 
                      Dispatcher.BeginInvoke(new Action(() => { 
                          AnimationView w = new AnimationView();
                          w.Show(); })); })); 
              t.Start();



              foreach (UserControl UC in UserControl)
              {
                  String fileName = UC.Name;

                  String filePath = "D:\ScreenShot";

                   SaveView(view, fileName,  filePath);

              }

        }

public static void SaveView(UserControl view, string fileName,  string destFolder)
        {

                Rect bounds = VisualTreeHelper.GetDescendantBounds(view);

                int width = (int)view.RenderSize.Width;
                int height = (int)view.RenderSize.Height;

                if (width == 0 || height == 0)
                {
                    width = 1920;
                    height = 1080;
                }

                RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

                DrawingVisual dv = new DrawingVisual();

                using (DrawingContext ctx = dv.RenderOpen())
                {
                    Size size = new Size(500, 500);
                    if (bounds.Size.IsEmpty == false)
                    {
                        if (bounds.Size.Height > 100)
                        {
                            size = new Size(bounds.Size.Width, bounds.Size.Height - 100);
                        }
                        else
                            size = new Size(bounds.Size.Width, bounds.Size.Height);
                    }

                    VisualBrush vb = new VisualBrush(view);
                    ctx.DrawRectangle(vb, new Pen(Brushes.Blue, 2), new Rect(new Point(0, 100), size));
                    ctx.DrawText(text, new Point(0, 20));
                    ctx.Close();
                }

                //  rtb.Render(view);
                rtb.Render(dv);

                try
                {
                    PngBitmapEncoder jpgEncoder = new PngBitmapEncoder();
                    jpgEncoder.Frames.Add(BitmapFrame.Create(rtb));

                    Byte[] _imageArray;

                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        jpgEncoder.Save(outputStream);
                        _imageArray = outputStream.ToArray();
                    }

                    //Try Find Save Path, if doesn't exists, create it.
                    if (Directory.Exists(destFolder) == false)
                        Directory.CreateDirectory(destFolder);

                    FileStream fileStream = new FileStream(Path.Combine(destFolder, fileName), FileMode.Create, FileAccess.ReadWrite);

                    fileStream.Write(_imageArray, 0, _imageArray.Length);

                    jpgEncoder.Save(fileStream);
                    fileStream.Close();


                }
                catch (Exception e)
                {
                    Log4Net.Instance.Info(System.Reflection.MethodInfo.GetCurrentMethod().ToString());
                    Log4Net.Instance.Info("Exception Generate Screenshot: " + fileName);
                    Log4Net.Instance.Info(e.StackTrace.ToString());
                    Debug.WriteLine(e.ToString());
                }
            }), DispatcherPriority.Loaded);
        }

I hope I can get your help.

Many thanks in advance.

Path Data references

$
0
0
I just started learning VB, but m book I am studying at the moment, doesn't explain items much. I would appreciate any help for the below question.  In Xaml.vb, when is <path used? In the <path data, what do the references refer to? For example, data="M 20, 100 S 10 ..." what is the meaning of M and S and the numbers.  thanks

WPF Resources on the TechNet Wiki

FTP IMAGE SORCE in WPF

$
0
0

Hi,

How to set image source as FTP Server Image in wpf with out downloading the image from ftp server.

Thanks


Become our FIRST Microsoft TechNet WPF Guru of 2014!!

$
0
0

Happy New Year!

Time for a fresh start!

We're looking for the first Gurus of 2014!!

This is your chance to make your mark on the Microsoft developer community.

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 to the one and onlyTechNet Wiki, for future generations to benefit from! You'll never get archived again!

If you are a member of any user groups, please make sure you list them in the Microsoft User Groups Portal. Microsoft are trying to help promote your groups, and collating them here is the first step.


How to load images in bulk onto a WPF Grid?

$
0
0

Hello,

I've loaded a bulk of images in visual studio as a .resx file and wanted to load them on a WPF  grid but the Image container had problems and I would have to do conversion, but after i thought about it, it seemed to be a bit unnecessary, since i should be able to do all of that in wpf.

I wanted to load an array with the images and load them into separate image containers using a loop. I could probably do this easier, without having to make conversions if i just did it in WPF? The problem is, I don't know how. I've done a little bit of searching on loading a bulk of images, but I've not found anything. Maybe I'm approaching it wrong? Would it be a waste of resources to load them all at program start-up and make them visible when needed? Any advice would be appreciate. 

Thanks


Malik


How to read data from database and put it in model

$
0
0

Hi esperts, i need help here, this is PersonViewModel.cs

namespace OliverCode.MVVM.ViewModel
{
    internal class PersonViewModel
    {
        public PersonModel Person { get; set; }

        private DelegateCommand savePersonCommand;

        public ICommand SavePersonCommand
        {
            get
            {                 
                if(savePersonCommand == null)
                    savePersonCommand = new DelegateCommand(new Action(SaveExecuted), new Func<bool>(SaveCanExecute));

                return savePersonCommand;
            }

        }

        public PersonViewModel()
        {
            //This data will load as the default person from the model attached to the view
            //Person = new PersonModel { FirstName = "John", LastName = "Doe", Age = 999 };
            //I want to read data from database using ado.net, read used datareader and put it in Person = new PersonModel
        }

        public bool SaveCanExecute()
        {
            return Person.Age > 0 && !string.IsNullOrEmpty(Person.FirstName) && !string.IsNullOrEmpty(Person.LastName);
        }

        public void SaveExecuted()
        {
            System.Windows.MessageBox.Show(string.Format("Saved: {0} {1} - ({2})", Person.FirstName, Person.LastName, Person.Age));
        }
    }
}

and this is Person.cs class

namespace OliverCode.MVVM.Model
{
    internal class PersonModel : System.ComponentModel.INotifyPropertyChanged
    {
        private string firstName;
        public string FirstName
        {
            get { return firstName; }
            set
            {
                firstName = value;
                OnPropertyChanged("FirstName");
            }
        }

        private string lastName;
        public string LastName
        {
            get { return lastName; }
            set
            {
                lastName = value;
                OnPropertyChanged("LastName");
            }
        }

        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                age = value;
                OnPropertyChanged("Age");
            }
        }

        #region INotifyPropertyChanged Members

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}

and this in PersonView.xaml

<UserControl x:Class="OliverCode.MVVM.View.PersonView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto"
    xmlns:local="clr-namespace:OliverCode.MVVM.ViewModel"><StackPanel Orientation="Vertical" Margin="4"><!--Here is where we the view gets a copy to the ViewModel Declaratively--><StackPanel.DataContext><local:PersonViewModel /></StackPanel.DataContext>        <StackPanel Orientation="Vertical" DataContext="{Binding Path=Person, Mode=TwoWay}" Margin="4"><StackPanel Orientation="Horizontal"><Label Content="First Name:" Margin="0,0,4,0"/><TextBox Width="250" Text="{Binding Path=FirstName}"/></StackPanel><StackPanel Orientation="Horizontal" Margin="0,5,0,0"><Label Content="Last Name:" Margin="0,0,4,0"/><TextBox Width="250" Text="{Binding Path=LastName}"/></StackPanel><StackPanel Orientation="Horizontal" Margin="0,5,0,0"><Label Content="Age:" Margin="35,0,4,0"/><TextBox Width="50" MaxLength="3" Text="{Binding Path=Age}"/></StackPanel></StackPanel>        <StackPanel><Button Content="Save" HorizontalAlignment="Right" Width="80" Command="{Binding Path=SavePersonCommand}"/></StackPanel></StackPanel></UserControl>


Instead hardcoded like Person = new PersonModel { FirstName = "John", LastName = "Doe", Age = 999 };

I want to read data from database using ado.net, read used datareader and put it in Person = new PersonModel

Thanks in advance


SelectionChanged event of WPF ComboBox returns Prior Selection not Current

$
0
0

There has to be something silly I'm doing here!

 

When I process a ComboBox's SelectionChanged event and then look at the ctype(e.source,ComboBox).Text value, I really expect to get the value that the ComboBox is now supposed to be set to. Instead, I'm getting the prior value! Help! I need to figure out the new value in the ComboBox Text property after it's been changed!

 

M

When check the CheckBox, getting focus problem

$
0
0

Hi,

I am testing of Check and Unchecked of CheckBox, but when I try to Check or UnCheck the CheckBox, focus goes to TabItem instead of CheckBox.

XAML is here.

<Window x:Class="TextBox_Focus.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"><DockPanel><Menu DockPanel.Dock="Top"><MenuItem Header="Startup"></MenuItem><MenuItem Header="Setup"></MenuItem><MenuItem Header="Transaction"></MenuItem></Menu><ToolBarTray DockPanel.Dock="Top" ><ToolBar KeyboardNavigation.TabNavigation="Once"><Button Content="Add"></Button><Button Content="Edit"></Button><Button Content="Delete"></Button></ToolBar></ToolBarTray><TabControl Name="tabMain"><TabItem Header="Tab 1" ><StackPanel  FocusManager.IsFocusScope="True"><TextBox></TextBox><CheckBox Content="Testing 1"></CheckBox><CheckBox Content="Testing 2"></CheckBox><CheckBox Content="Testing 3"></CheckBox></StackPanel></TabItem><TabItem Header="Tab 2" ><StackPanel  FocusManager.IsFocusScope="True"><TextBox></TextBox><CheckBox Content="Testing 1"></CheckBox><CheckBox Content="Testing 2"></CheckBox><CheckBox Content="Testing 3"></CheckBox></StackPanel></TabItem></TabControl></DockPanel></Window>


WPF password strength meter?

$
0
0

Hi ya, I'm looking for some sample of info about how to implement a strength indicator along with one TextBox for a password.

My goal is clear: just show the user if the password proposed is weak, strong, or very strong. Only for their information, not being compulsory to save a password in a concrete level of difficulty

Thanks in advance,


Primary platform is Windows 7 Ultimate 64 bit along with VS 2012/Sql2k8 for WPF/SilverLight projects.

Setting the focus. it does fail

$
0
0

Hi all of you, I've got a couple of issues with the focus of my view.

I wonder whether related with PasswordBox control or not

The first issue:

  <PasswordBox Margin="48,14,56,14" x:Name="pwdnou" 
        FocusManager.FocusedElement="{Binding ElementName=pwdnou}"
            PasswordChanged="pwdnou_PasswordChanged"
                     
            Grid.ColumnSpan="2" Grid.Column="1" Foreground="MidnightBlue" BorderBrush="Gray"
            HorizontalAlignment="Center" VerticalAlignment="Center" Height="24" Width="100" />

        <PasswordBox Margin="48,14,56,14" x:Name="pwdnouconfirmar"
            Style="{StaticResource PasswordBoxVistaStyle}"
                   LostFocus="pwdnouconfirmar_LostFocus"
            Grid.ColumnSpan="2" Grid.Column="1" Foreground="MidnightBlue" BorderBrush="Gray"
            HorizontalAlignment="Center" VerticalAlignment="Center" Height="24" Width="100" Grid.Row="1" />

It does not work at all; when I load my view I don't see the cursor on "pwdnou" PasswordBox, in fact, the cursor is not visible at all.

Nevertheless if I write pwdnou.Focus() in OnLoaded Grid event code-behind it does works properly. But I don't like to use code-behind for that.

The second one is when I try to set the focus in that same PasswordBox from the Lostfocus event on the second one PasswordBox (pwdnouconfirmar). Here, amazingly does not work.

What am  I missing here?

 Private Sub pwdnouconfirmar_LostFocus(sender As Object, e As RoutedEventArgs)
        If pwdnou.Password <> pwdnouconfirmar.Password Then
            sMessageTranslated = My.Resources.MasterGIT.APP_ERROR3
            WpfMessageBox.Show(sMessageTranslated, Conectividad.NameOfApplication, WpfMessageBoxButton.OK, WpfMessageBoxImage.Error)
            pwdnou.Password = String.Empty
            pwdnouconfirmar.Password = String.Empty
'            pwdnou.Focusable = True
            pwdnou.Focus()



            'Exit Sub

        End If

Thanks in advance for any input or hint provided


Primary platform is Windows 7 Ultimate 64 bit along with VS 2012/Sql2k8 for WPF/SilverLight projects.


ClickOnce and satellite assembly with custom resources

$
0
0

Hi all, I have a WPF Application that uses ClickOnce. In my application I reference a satellite assembly that contains all the resources (messages, images, styles) for a specific customer and this assembly change from customer to customer. It is possible to use ClickOnce to deploy any updates of my application avoiding to delete this satellite assembly on the client machine?

Thanks in advance!

ScrollIntoView on datagrid won't work if to many items are added...

$
0
0

hey,

if i use ScrolIntoView on a datagrid , it won't work if ti add to many items to the View. Means, during runtime i fill the datagrid with approximatly 500 items. After all items are added in Need to select and scrollintoview a particular Item. But this doesn't happen, cause (i suggest) the datagridis filled within a second thread, and is not ready if my code set the selecteditem and the scrollintoview method. Sooo, is there anyone with experience or is there an Event that i can use to handle the Situation???

thanks and bye


creating and editing a wpf datagrid

$
0
0

Hi,

      I am just migrating from Windows Forms to WPF. I need immediate help on creating an unbound datagrid with 2 columns ('Type' and 'Telephone No') and adding records to it. Can someone please give me a comprehensive code in vb.net / xaml for this

Thanks & regards

Sanjish

how can i use the period delimited hierarchy function of the SortMember Path function in CodeBehind??

listBox.SelectedItem problem

$
0
0

Im using D&D from list box to textBox and the problem is that the you can just click on item(the item markedwith blue color) let say the first item in the list and than you can go to the list and with the mouse drag different item let say the last item in the list but the item that was actually dragged is the item which you selected via click which is marked with blue color...      i.e. the first item.

while debug I Saw that the item which you get in the following code is first item which you click and mark as blue and not the item that you actually dragged,any idea how to solve it?

you can click and mark any item on the listBox but drag different item while the previous item is marked with blue color...

var listBox = sender asListBox;if(listBox.SelectedItem!=null){var mySelectedItem = listBox.SelectedItemasUser;

Viewing all 18858 articles
Browse latest View live


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