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

New WPF Videos

$
0
0

I just noticed a couple of new videos about recent improvements to Visual Studio and XAML editing that WPF developers could be interested in.

You may well be aware of all of these, but you never know....

https://channel9.msdn.com/Series/Visual-Studio-2015-Enterprise-Videos/Code-Editor-Enhancements-for-XAML-Developers#time=0s

I've not really found regions in xaml terribly useful so far but I know some people were asking for this.

More significant (IMO) is peek editing, which is handy.

In order to implement this they've made some fundamental changes.

This explains a couple of things I've noticed.

VS2015 now seems a bit more prone to spurious errors in xaml that disappear when you run. I guess there's still a few kinks there to iron out.

Commenting out xaml is now more flexible than it used to be. At one time you had to go with pretty much a whole control or it wouldn't work. Now you can comment out pieces inside complex controls.

https://channel9.msdn.com/Series/Visual-Studio-2015-Enterprise-Videos/Windows-Presentation-Foundation-Application-Development#time=0s

Well worth a review even if you think you probably knew all this.

Clearly, any demonstration of optimisation within a couple of minutes timeframe is going to gloss over some things. Don't let the almost trivial drag-a-thread-snippet distract you. The performance analysis tools are now much more useful than they once were. Still not up to other dedicated tools out there, but the VS version is totally free.

Anyhow.

I liked these vids and it's good to see WPF getting some attention.

WPF is still easily the windows desktop application software of choice and it's good to hear it mentioned without any negative label.


Hope that helps.

Technet articles: WPF: Layout Lab; All my Technet Articles


button with rounded corners

$
0
0

i don't want to learn templates and don't want my buttons to be glossary , i just want the corners of my simple button to be rounded.

thousands of examples , not one SIMPLE example of button with rounded corners anywhere.

i tried this:

<ButtonHeight="150"Width="200"Margin="100,20,0,0"><BorderCornerRadius="15"BorderBrush="Black"BorderThickness="20"></Border></Button>

but all i get is a button with a black dot inside it:

 

 

WPF line spacing code for richtextbox

$
0
0
using System.Windows.Media.Imaging;

using System.Printing;
using System.Windows.Xps;
using System.Xml;
using System.Windows.Markup;

using System.Diagnostics;
using System.Collections.Generic;

using System.Linq;
using System.Runtime.InteropServices;

 public partial class rtbRuler : Window
    {

  private static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref PARAFORMAT lParam);
        const int PFM_SPACEBEFORE = 0x00000040;
        const int PFM_SPACEAFTER = 0x00000080;
        const int PFM_LINESPACING = 0x00000100;
        const int SCF_SELECTION = 1;
        const int EM_SETPARAFORMAT = 1095;



 private void setLineFormat(byte rule, int space)
        {
            PARAFORMAT fmt = new PARAFORMAT();
            fmt.cbSize = Marshal.SizeOf(fmt);
            fmt.dwMask = PFM_LINESPACING;
            fmt.dyLineSpacing = space;
            fmt.bLineSpacingRule = rule;
            richTextBox1.SelectAll();
            SendMessage(new HandleRef(richTextBox1, richTextBox1.Handle),
                         EM_SETPARAFORMAT,
                         SCF_SELECTION,
                         ref fmt
                       );
        }
        private void ignoreLineSpacing_Click(object sender, EventArgs e)
        {
            setLineFormat(0, space);
        }
        private void oneandHalfSpacing_Click(object sender, EventArgs e)
        {
            setLineFormat(1, space);
        }
        private void doubleSpacing_Click(object sender, EventArgs e)
        {
            setLineFormat(2, space);
        }
        int space = 0;

        public struct PARAFORMAT
        {
            public int cbSize;
            public uint dwMask;
            public short wNumbering;
            public short wReserved;
            public int dxStartIndent;
            public int dxRightIndent;
            public int dxOffset;
            public short wAlignment;
            public short cTabCount;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
            public int[] rgxTabs;
            // PARAFORMAT2 from here onwards
            public int dySpaceBefore;
            public int dySpaceAfter;
            public int dyLineSpacing;
            public short sStyle;
            public byte bLineSpacingRule;
            public byte bOutlineLevel;
            public short wShadingWeight;
            public short wShadingStyle;
            public short wNumberingStart;
            public short wNumberingStyle;
            public short wNumberingTab;
            public short wBorderSpace;
            public short wBorderWidth;
            public short wBorders;
        }
This is Windows Form code I am trying to convert to wpf code

WPF Ribbon theme customization

$
0
0

Hello everybody!

 

Is it possibile to customize the builtin wpf ribbon themes?

 

Thank you very much!

Ribbon Themes

$
0
0
Does the official WPF Ribbon contain any themes we can use, such as Office2007Blue? I tried using the Office one and it appears it is not available.

Free WPF Ribbon

$
0
0
How do I get a free WPF ribbon control from Microsoft ??
Thanks in advance

how do I do xxx with the new WPF ribbon

$
0
0

First, let me say a big YAY to the recent release of the update WPF ribbon.  Just started looking through the samples, and it looks pretty good.  Now, I have a couple of questions about things that I was doing with the ribbon CTP, and would like to know how to do with the new ribbon...

1) Select a theme.  The CTP had blue, silver, black that could be set by merging in a resource dictionary
    <ResourceDictionary Source="/RibbonControlsLibrary;component/Themes/Office2007Blue.xaml"/>

Do we have any such choices with the new ribbon? It's great that this looks like windows 7 style.  Is there support for office 2007 themes?  Like if somebody actually liked the old "frisbee" button?

2) Reference resources from the ribbon.  In the CTP, I found it useful to borrow some of the resources defined in the ribbon for use in other places in my app. This allowed me to match fonts, colors, gradients, etc.. in a few places.  Like I could do stuff like this:

    <StatusBarItem TextElement.Foreground="{StaticResource {x:Static r:RibbonSkinResources.RibbonFontColorBrushKey}}" />

And my status bar text was the same color as the ribbon text.  Maybe that was a bad idea, but it sure was handy.

Thanks


roger reynolds

MS Ribbon for WPF - How can I change the skin ?

$
0
0
Hello,

I'm using the latest version of MS Ribbon for WPF (3.5.40729.1) with Visual Basic 2010 Express and will change the skin of the ribbon.
The solution by MSDN (see below) doesn't work, and in the object browser I can't find the SkinRessources.

Solution by MSDN:
<Window.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="/RibbonControlsLibrary;component/themes/office2007silver.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Window.Resources>

How can I change the skin ?

[WPF] How to start a storyboard defined in a style?

$
0
0

XAML:

<Window.Resources><Style x:Key="GridStyle1" TargetType="{x:Type Grid}"><Style.Resources><Storyboard x:Key="Storyboard1"><ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="{x:Null}"><EasingColorKeyFrame KeyTime="0:0:1" Value="Red"/></ColorAnimationUsingKeyFrames></Storyboard></Style.Resources><Setter Property="Background" Value="White"/></Style></Window.Resources><Grid x:Name="grid" Style="{DynamicResource GridStyle1}" MouseDown="Grid_MouseDown"/>

C# 1:

            Style style = this.Resources["GridStyle1"] as Style;
            Storyboard storyboard = style.Resources["Storyboard1"] as Storyboard;

            storyboard.Begin();

Exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: No target was specified for 'System.Windows.Media.Animation.ColorAnimationUsingKeyFrames'.

C# 2:

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Style style = grid.Style;
            Storyboard storyboard = style.Resources["Storyboard1"] as Storyboard;

            storyboard.Begin();
        }

Exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: No target was specified for 'System.Windows.Media.Animation.ColorAnimationUsingKeyFrames'

Changing

            storyboard.Begin();

to

            storyboard.Begin(this);

results in no response of the app when pressed mouse down.

Note: The goal is to start a storyboard from code behind, not using triggers in XAML.

wpf how do you in a richtextbox highlight a line of text and show the size of the font in a messagebox

$
0
0
how do you in a rich textbox highlight a line of text and show the size of the font in a message box

How to get updated page information through C# WebBrowser when updatePanel AJAX event happens?

$
0
0
   

I am automating a scenario in WPF using WebBrowser control. Code snippet is as follows

string id = paginationControlProcessing[1].PageCtrl.id;   

webDoc.GetElementById(id).GotFocus += new HtmlElementEventHandler(wb_OnGotFocus_PaginationControls);   

webDoc.GetElementById(id).Focus();   

webDoc.GetElementById(id).RaiseEvent("onChange");   

webDoc.InvokeScript("__doPostBack", new object[] { "ctl00$ContentPlaceHolder1$pgControl$nextPageLink", "" });


When the page changes through pagination control, I am able to hit the event handler for focus change. Problem is happening when pagination controls are hit where I am not able to retrieve the data for 2nd and 3rd page.

Pagination control 1Pagination Control 2Pagination Control 3

I can do the page navigation and it works in the WebBrowser control. Data is also updated in the table to which these ASP.net AJAX controls are attached. In the event handler, when I look into the content of object WebBrowser1, it does not contain the content of new data that appears in the UpdatePanel control. Data for the control when 2 and 3 are clicked comes through UpdatePanel ASP.Net control.

What event can be used to capture the data coming for UpdatePanel control from server?

    

Regards Atul Kumar

Adding child to node.

$
0
0

Hi, i have a treeview in silverlight.

I can add the root with child nodes by doing like this

            Thing st = new Thing();
            st.StatusBrush = new SolidColorBrush(Colors.Purple);
            st.Name = strSubNodes[2].ToString();
            tvi.Children.Add(st);
            st.Children.Add(
              new Thing { StatusBrush = new SolidColorBrush(Colors.Purple), Name = strSubNodes[2].ToString() }
              );

The Thing looks like this:

    public class Thing
    {
        public SolidColorBrush StatusBrush { get; set; }
        public string Name { get; set; }
        public ObservableCollection<Thing> Children { get; set; }
    }

But when i add the root nodes first, and later want to add child nodes to the various root nodes, i have yet to find a way to add child nodes to the root. Latest try is this code. but the Children is null, so i cannot add to it (NullPointerReference)

        private void AddNode(string strNode, string[] strSubNodes)
        {

            Thing tvi = FindNode(strNode);

            if (tvi == null)
            {
                AddRoot(strNode);
                tvi = FindNode(strNode);
            }


            foreach (Thing rti in tv.Items)
            {
                //tb3.Text += "rti: " + rti.Name + "\n";
                if (rti.Name == strNode)
                {

                    rti.Children.Add(
                new Thing { StatusBrush = new SolidColorBrush(Colors.Purple), Name = strSubNodes[2].ToString() }
                );
                    return;
                }
            }
        }

        private Thing FindNode(string strNode)
        {
            foreach (Thing tvi in tv.Items)
            {
                if (tvi.Name == strNode)
                {
                    return tvi;
                }
            }

            return null;
        }


WPF MVVM monitor directory

$
0
0

I have a WPF MVVM application that has a couple of forms, one that creates files on local disk. When the application starts I need to start Timer that will monitor a folder and send those text files to a service. The computer it sits on doesn't always have a connection that is why I need to write them to the local machine.  Where is the best place to put this code Should I just start something in the code behind for the main window or should it be in another ViewModel?

Modify TreeViewItems - Does not change visually

$
0
0

Hi.

I have this treeview, programatically created (adding the nodes)


When each child nodes OPC-Tag changes, (it comes with 1 or 0).
The OPC-Tag comes in just nicely.

And each time the tags updates i call this function

        private void UpdateStatuses(string strTag, string sStatus)
        {
            foreach (Thing tvi in tv.Items)
            {
                bool bRed = false;
                foreach (Thing tva in tvi.Children)
                {
                    if (tva.Tag == strTag)
                    {
                        if (sStatus == "0")
                        {
                            tva.StatusBrush = new SolidColorBrush(Colors.Red);
                            tva.Name = strTag;
                            bRed = true;
                        }
                        else
                        {
                            tva.StatusBrush = new SolidColorBrush(Colors.Green);
                        }
                    }
                }
                tb3.Text = "\nRed: " + bRed;
                if (bRed)
                {
                    tvi.StatusBrush = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    tvi.StatusBrush = new SolidColorBrush(Colors.Green);
                }
            }
            tv.ExpandAll();
        }


But the Illipse does not change the color, and where i try to change the

tva.Name = strTag;

The child node still have the old name.

What i am trying to accomplis is

* Reflect the color of each node according to the tag value
* Update the parent node so, if any listed node is not green, the parent node should be red, else be green.

Each item is this class

    public class Thing
    {
        public SolidColorBrush StatusBrush { get; set; }
        public string Name { get; set; }
        public string Tag { get; set; }
        public ObservableCollection<Thing> Children { get; set; }
    }


Data binding does not work in XPS

$
0
0

Hi,

I'm generating XPS reports in a non-WPF application. Sometimes, the bound data is not rendered in the report and I cannot understand why.The GUI is correctly rendered, but XPS is not. I have searched the net for days. It seems at least a few others are experiencing the same problem. Let's create a sample project that demonstrates the problem! Please note that I cannot print the Visual directly since the printing function may be used in a service or similar.

1) Create a WPF project called WpfApplication1.
2) Replace the MainWindow class with the code below.
3) Add a my_template.xaml file to the solution and change its Build Action to "None".
4) Add the my_template.xaml file (code below) to the application's resources (Resources.resx).
5) Add references to ReachFramework and System.Printing.
6) Run the application! The GUI shows the text "test", but the generated XPS document (saved on your Desktop) does not!

Note the trace window. This is the last trace after the dispatcher has updated the bindings:

System.Windows.Data Warning: 89 : BindingExpression (hash=8761922): TransferValue -using final value 'test'

What is going on?!

MainWindow.xaml.cs

public partial class MainWindow : Window
{
 public MainWindow()
 {
  InitializeComponent();

  DataContext = "test";
 }

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
  var documents = new List<FixedDocument>();

  var document = XamlReader.Parse(WpfApplication1.Properties.Resources.my_template) as FixedDocument;

  InjectData(document, DataContext);

  documents.Add(document);

  string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  string filename = System.IO.Path.Combine(path, "XpsTest.xps");

  using (var stream = File.Create(filename))
  {
   ConvertToXps(documents, stream);
  }

  foreach (var fixedPage in document.Pages.Select(pageContent => pageContent.Child))
  {
   fixedPage.Children.Clear();
  }
 }

 protected void InjectData(FixedDocument document, object dataSource)
 {
  document.DataContext = new { MyTextData = dataSource };

  // we need to give the binding infrastructure a push as we
  // are operating outside of the intended use of WPF
  var dispatcher = Dispatcher.CurrentDispatcher;
  dispatcher.Invoke(
     DispatcherPriority.SystemIdle,
     new DispatcherOperationCallback(delegate { return null; }),
     null);
 }

 protected void ConvertToXps(IEnumerable<FixedDocument> fixedDocuments, Stream outputStream)
 {
  var package = Package.Open(outputStream, FileMode.Create);
  var xpsDoc = new XpsDocument(package, CompressionOption.Normal);
  var xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);

  // XPS documents are built using fixed document sequences.
  var fixedDocSeq = new FixedDocumentSequence();

  foreach (var fixedDocument in fixedDocuments)
  {
   var docRef = new DocumentReference();
   docRef.BeginInit();
   docRef.SetDocument(fixedDocument);
   docRef.EndInit();
   ((IAddChild)fixedDocSeq).AddChild(docRef);
  }

  // Write out our fixed document to XPS.
  xpsWriter.Write(fixedDocSeq.DocumentPaginator);

  xpsDoc.Close();
  package.Close();
 }
}

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Window_Loaded"
        Title="MainWindow"
        Width="793.92" Height="1122.24" Margin="100"><Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="200"><TextBlock Background="LightGray" Text="{Binding}"
                   FontSize="36"/></Grid></Window>

my_template.xaml

<FixedDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><PageContent><FixedPage Width="793.92" Height="1122.24" Margin="100"><Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="200"><TextBlock Background="LightGray" Text="{Binding MyTextData,PresentationTraceSources.TraceLevel=High}"
                           FontSize="36"/></Grid></FixedPage></PageContent></FixedDocument>


Opening new Wpf window from Wpf userControl Hosted in Winform

$
0
0

I have an existing winforms application which we are migrating towards wpf. I have a Winform that loads a Wpf user control, showing a list of items. In that list, there is an edit button that I need to allow the detail of the list item to edited  I have created a Wpf window built to handle the edit.

What I need to do is to open the edit window from the click of the datagrid template button. I have the code working to load the list, and to enter the onclick event of the button.  My problem is that I can't get the edit window to load.  I have seen a few issues where this was addressed, but it was address 5+ years ago and it does not appear applicable to the latest .Net versions.

Can someone point me to the best solution for this.


Joel WZ

Adding textbox to panel in code

$
0
0

I'm unable to add a textbox to a stackpanel in code.  The label adds OK, just not the textbox.  I would use a Windows control for the label but the "Content" property is not available to me.  

I'm attempting to add one label and one textbox in 4 stackpanels.

Xaml:

<StackPanel x:Name="pnlxxx0" Orientation="Horizontal" Background="LightYellow" Margin="0,151,0,-33"></StackPanel><StackPanel x:Name="pnlxxx1" Background="LightPink" Margin="0,182,0,-66"></StackPanel><StackPanel x:Name="pnlxxx2" Background="LightGreen" Margin="0,215,0,-96"></StackPanel><StackPanel x:Name="pnlxxx3" Background="LightSalmon" Margin="0,245,0,-125"></StackPanel>

Thanks.


emcustom

WPF datagrid update when click button

$
0
0

Hello. I have a small problem. I have a datagrid with 4 columns (description, date, id and a button for each row). Datagrid is not read_only, so I can modify description cell value.

This datagrid is populated from MS SQL database view. In that View I have also column last_update.

How can I, when I press that button for a row to update column last_update from my database coresponding to id column from datagrid?

Profiling in a multi threaded application

$
0
0

Hi,

We are using a multi threaded C# WPF Application.

For the development I am using VS 2013 Express Desktop version.

To understand how much time being taken by a piece of code can I use StopWatch Class to get the time being taken for the code to execute.

Why am I asking this question is after the Stopwatch timer starts, if the thread is pushed away by a highest priority thread then don't we get wrong results.

What are the other methods apart from using ANTS Peformance profiler does Visual Studio 2013 Express supports any tools.

Best Regards,

GSR


How to use ViewModelLocator in PRISM 6 (Unity) modules?

$
0
0

We have a small application setup with PRISM 6 and Unity bootstrapper. I want to use the ViewModelLocator to bind a ViewModel to my view. This works in the "base module" (the one with Shell and bootstrapper) but it seems that there are some issues when using it in other modules.

Below you can find the classes for View (XAML and code behind) and for ViewModel. The binding works if I set the DataContext in the code behind manually. When debugging it I found out that the ViewModel class is never instantiated so I guess the VML cannot find the VM because of wrong configuration.

Can you find the issue or have an idea what configuration I did forget?

namespace CommunicationModule.Views
{

    public partial class CommunicationView : UserControl, IView
    {
            public CommunicationView()
            {
                InitializeComponent();
            }
        }
}

<UserControl
     x:Class="CommunicationModule.Views.CommunicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:View="clr-namespace:CommunicationModule.Views"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"><Grid DataContext="{Binding ModelList, UpdateSourceTrigger=PropertyChanged}" Width="320" Height="300"><Grid.Resources><DataTemplate x:Key="DataTemplate"><Border Name="border" BorderBrush="DarkSlateBlue" BorderThickness="2"
                 CornerRadius="2" Padding="5" Margin="5"><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition MaxWidth="30"/><ColumnDefinition /><ColumnDefinition /></Grid.ColumnDefinitions><Image Grid.Row="0" Grid.Column="0" Source="{Binding Path=IconUri}" HorizontalAlignment="Left" /><TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Title}" FontSize="12" FontWeight="Bold" /><TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=ContentShort}"/></Grid></Border></DataTemplate></Grid.Resources><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><!-- UI --><DockPanel Grid.ColumnSpan="2" Margin="0,0,10,0"><!-- Title --><Label DockPanel.Dock="Top" FontSize="18" Margin="5" Content="Wichtige Meldungen"/><!-- Data template is specified by the ItemTemplate attribute --><ScrollViewer><ListBox Name="listBox"
            SelectionMode="Single"
            ItemsSource="{Binding}"
            ItemTemplate="{StaticResource DataTemplate}"
            HorizontalContentAlignment="Stretch"
            IsSynchronizedWithCurrentItem="True"
            Margin="5,0,5,5" Width="280"/></ScrollViewer></DockPanel></Grid></UserControl>

namespace CommunicationModule.ViewModels
{
    public class CommunicationViewViewModel : BindableBase
    {
        private List<CommunicationModel> _modelList = (new CommunicationModelBO()).getCommunicationItems(); //= new List<CommunicationModel>();
        private readonly IRegionManager _regionManager;

        public List<CommunicationModel> ModelList
        {
            get { return _modelList; }
            set { SetProperty<List<CommunicationModel>>(ref _modelList, value); }
        }

        public CommunicationViewViewModel(IRegionManager regionManager)
        {
          _regionManager = regionManager;
        }
    }
}

Viewing all 18858 articles
Browse latest View live


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