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

The Bullet in a RadioButton becomes invisible after applying a new theme at runtime (via Application.Current.Resources)

$
0
0

Hi All,

I have a bunch of radio buttons which work happily in either the "ExpressionDark.xaml" or "ExpressionLight.xaml" resource dictionary themes when set at design time.  However when I change the theme at runtime, the radio buttons no longer show their current value - the bullet is invisible, like nothing is selected. If I then force the radio button to update itself, by clicking on one of its alternate selections, then it will start showing the bullet properly again.

Here is an example of two radio buttons on one of my windows:

<StackPanelOrientation="Horizontal"><LabelWidth="55"Content="Depth:"HorizontalContentAlignment="Right"VerticalAlignment="Center"/><RadioButtonWidth="45"GroupName="Depth"IsChecked="{Binding DepthM}"Content="M"HorizontalAlignment="Left"VerticalAlignment="Center"Margin="3,3,0,3"/><RadioButtonWidth="55"GroupName="Depth"IsChecked="{Binding DepthM,Converter={StaticResource BooleanInverterConverter},Mode=OneTime}"Content="FT"HorizontalAlignment="Left"VerticalAlignment="Center"Margin="0,3,0,3"/></StackPanel>

Also, here is the code which loads the new theme at runtime:

publicvoid LoadUITheme()
{string resourceFileName = (this.UIThemeIsDark ? "ExpressionDark.xaml" : "ExpressionLight.xaml");
 ResourceDictionary resources = null;using (FileStream fs = new FileStream("Themes\\" + resourceFileName, FileMode.Open, FileAccess.Read))
 {// Get the root element, which must be a ResourceDictionary 
  resources = (ResourceDictionary)XamlReader.Load(fs);
 }
 Application.Current.Resources = resources;
}

Any ideas why this is happening or a possible workaround?

Much appreciated,

Harvey

 


Load a Multilevel XML file into a WPF DataGrid

$
0
0

Hi,

I've learned how to load an xml file into a WPF DataGrid using dataSet.ReadXml method. And assigning Dataset input to ItemsSource of a DataGrid.

This works well as long as the xml file has no multilevel elements in it.

I have tried loading a multilevel xml file using a CollectionViewSource, binding DataGrid columns to xml attribute values of xml elements at different levels. It worked.

But how do I load a multilevel xml file into a WPF DataGrid without using Bindings.

Example XML file:

<?xml version="1.0" encoding="utf-8" ?>
<data>
  <drive>
    <label>Area 51</label>
    <date>12/10/2012</date>
    <description>testing site</description>
    <status>Valid</status>
    <membership>
      Username="Jsmith"
      Bool="or"
      username="MGordon"
    </membership>
  </drive>
  <drive>
    <label>Apollo</label>
    <date>12/04/2010</date>
    <description>fly to the Moon</description>
    <status>Terminated</status>
    <membership>
      Username="DKerr"
      bool="and"
      Username="Sremi"
      bool="or"
      Group="ApolloReadOnly"
    </membership>
  </drive>
  <drive>
    <label>Deep Impact</label>
    <date>12/06/08</date>
    <description>Exploring Comet Temple</description>
    <status>Achieved</status>
    <membership>
      <collection>
        Username="Gblaine"
        Group="SSnype"
        group="Wesson"
        bool="or"
        Computer="Exec-02"
      </collection>
    </membership>
  </drive>
</data>

Any help appreciated.

Thank you.

Harika


Last active Application running on Windows (focus)

$
0
0

Hi! 

I would like to know how can I understand what the last active app running on windows before my app starts and while it is running. For instance, I can focus desktop and then focus my app. Can I get that the user was on Desktop and not in a browser for example. 

Thanks

Visual Studio 2015 and PRISM compatibility issue

$
0
0

I downloaded the Microsoft Patterns & Practices sample code for Prism Interactivity.

http://www.microsoft.com/en-us/download/details.aspx?id=42537

If I open this project with Visual Studio 2013, and open up the InteractionRequestView.xaml, everything looks fine.  I can see the UserControl in the designer and no errors.  Also I can build and run without a problem.

If I open this project with Visual Studio 2015, and open up the InteractionRequestView.xaml, I cannot see the design-time of the UserControl.  It states Invalid Markup.  If I look at the errors panel, it shows that on the line

<prism:InteractionRequestTrigger SourceObject="{Binding RequestShowConfiguration, Mode=OneWay}">

has an error that states:  "The local property 'Actions' can only be applied to types that are derived from 'TriggerBase'.  The code still compiles and runs correctly.  This would not be much of an issue as it would an annoyance, if it were not for the fact that the designer does not load because of 'invalid markup'.

Does anyone know how to fix this issue?  Is anyone else having the issue?  The code is obviously correct, since it runs.  All I can determine is there is some issue in the IDE.

Thanks,

Michael

WPF: Where is animation updated event?

$
0
0

Situation: Animation updates a property.

Goal: Call my method every time, when animation updates the property.

Problem: I can't find such an event.

Question: Where is the event to detect every property updating done by animation?

Code:

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

            this.Loaded += MainWindow_Loaded;
        }

        Line line;

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Canvas canvas = new Canvas();
            canvas.Background = Brushes.Black;
            this.Content = canvas;

            line = new Line();
            line.Stroke = Brushes.White;
            line.X1 = 0;
            line.Y1 = 0;
            line.X2 = 100;
            line.Y2 = 100;

            canvas.Children.Add(line);

            Animation();
        }

        private void Animation()
        {
            DoubleAnimation DB = new DoubleAnimation();
            DB.By = 100;
            DB.AutoReverse = true;
            DB.RepeatBehavior = RepeatBehavior.Forever;
            DB.Duration = new Duration(TimeSpan.FromMilliseconds(100));

            string name = "line";
            RegisterName(name, line);

            Storyboard SB = new Storyboard();
            Storyboard.SetTargetName(DB, name);
            Storyboard.SetTargetProperty(DB, new PropertyPath(Line.X2Property));
            SB.Children.Add(DB);

            SB.Begin(this, true);
        }
    }

RichTextControl -Font size is not written correctly to rtf file

$
0
0

Hi,

I have a richtextbox control. I am saving its content in an RTF document using the below code: -

            TextRange textRange = new TextRange(RichTextCtrl.Document.ContentStart,
                                                RichTextCtrl.Document.ContentEnd);
            FileStream file = new FileStream("BBB.rtf", FileMode.Create);
            textRange.Save(file, System.Windows.DataFormats.Rtf);
            file.Close();

If I change the font size to 22 using below code :-

           RichTextCtrl.Selection.ApplyPropertyValue(Inline.FontSizeProperty, "22");
            RichTextCtrl.FontSize = 22;

The font size in RTF file is written as "fs33" that means font size of 16.5 as per the RTF standards.

Could you please help me to solve this issue. If I open the rtf file in word also it shows 16.5.

This is the rtf output which is written.

{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs24\f0\cf0 \cf0\ql{\fs33\f0 {\ltrch I have a richtextbox control.}\li0\ri0\sa100\sb100\fi0\ql\par}
}
}

Regards,

Sharda.

Unable to cast object of type 'MS.Internal.Controls.AddInHost' to type 'System.Windows.Controls.UserControl'

$
0
0

Hi,

I am facing problem for implementing WPF addin framework in my application. In my application, I have to create instance of Usercontrol into separate appdomain and pass the reference to host application which is running into another appdomain

I have created usercontrol instance separate appdomain and cast it to "System.Windows.FrameworkElement" as per addin framework guideline and I am able to pass reference of framework instance into host application. But when I am trying to convert FrameWorkElement into usercontrol in hostapplication appdomain, I am getting exception  "Unable to cast object of type 'MS.Internal.Controls.AddInHost' to type 'System.Windows.Controls.UserControl'."

Can any one please tell me whether it is possible to convert Framework element into userControl.

Regards

Tihomir Blagoev

Localize source code comments

$
0
0

Hi to all the ML.

In a WPF UserControl I'd like to localize the "PropertyTabName" and the "DescriptionToolTip"of a DependencyPropertywhendisplayed in the property grid.

 ''' <summary>
        ''' Identifies the char size Dependency Property
        ''' </summary>
        Public Shared ReadOnly FontSizeProperty As DependencyProperty = DependencyProperty.Register("FontSize", GetType(Double), GetType(Ruler), New FrameworkPropertyMetadata(CDbl(16.0), FrameworkPropertyMetadataOptions.AffectsRender))

        ''' <summary>
        ''' Gets or sets the size of the chars in the ruler.
        ''' </summary><ComponentModel.Category("PropertyTabName")><ComponentModel.Description("DescriptionToolTip")>
        Public Property FontSize() As Double
            Get
                Return DirectCast(GetValue(FontSizeProperty), Double)
            End Get
            Set
                SetValue(FontSizeProperty, Value)
            End Set
        End Property
Any suggestions onhow to do?


Putting Each Item in a list box inside of a custom control

$
0
0

Hi All,

I am working on a project where I need to have a list of items that the user has chosen.  I want to make it so that the user can easily remove items from the listbox.  I think that the best way to do this is to wrap each item that is in the listbox inside of a custom control that has a "X" that removes the item from the listbox.

1.  Do I have the right idea?

2.  How do I do this?  From a programming perspective, I want to be able to access the items in the listbox as if they were not wrapped.

Thanks!

default font size of RichTextBox is 12?

$
0
0

I have a simple example program with a ComboBox contained in a toolbar and a RichTextBox.

The example program is to show that when a ComboBox with font sizes in the toolbar is changed, the selected text in the RichTextBox will change to the selected font size. Conversely, when text in the RichTextBox is changed, the ComboBox will change to reflect the font size of the selected text in the RichTextBox

When click in the empty RichTextBox to begin typing but nothing has been typed yet, the SelectionChanged( ) event is fired and the ComboBox changes to 12.

Is this value of 12 a default value? 

The code :

<Window x:Class="Example.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="600" Width="400"><DockPanel><ToolBarTray  x:Name="toolbar"
				 DockPanel.Dock="Top"
				ComboBox.SelectionChanged="toolbar_SelectionChanged"><ToolBar><ComboBox x:Name="fontSize"
					  MinWidth="40"
					  ToolTip="Font Size"></ComboBox><ComboBox x:Name="fontFamily"
						  MinWidth="100"
						  ToolTip="Font Family"></ComboBox></ToolBar></ToolBarTray><RichTextBox x:Name="rtb"
					 BorderThickness="0 5 0 0"
					 SelectionChanged="rtb_SelectionChanged" /></DockPanel></Window>

and

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


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

			for (double i = 8; i < 48; i += 2)
			{
				fontSize.Items.Add(i);
			}
		}

		private void toolbar_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			ComboBox source = (ComboBox) e.OriginalSource;

			if (source == null)
				return;

			switch (source.Name)
			{
				case "fontFamily":
					rtb.Selection.ApplyPropertyValue(TextBlock.FontFamilyProperty, source.SelectedItem);
					break;
				case "fontSize":
					rtb.Selection.ApplyPropertyValue(TextBlock.FontSizeProperty, source.SelectedItem);
					break;
			}

			rtb.Focus();
		}

		private void rtb_SelectionChanged(object sender, RoutedEventArgs e)
		{
			object size = rtb.Selection.GetPropertyValue(TextBlock.FontSizeProperty);

			if (size != DependencyProperty.UnsetValue)
				fontSize.SelectedValue = (double)size;
		}
	}
}

Steps to Draw a Soccer Field Diagram

$
0
0

How would YOU structure your XAML elements and what objects would you use in what navigational oultine?  I want a see a soccer field with all goal lines, touch lines, corner arcs, center circle, penalty area and goal area, etc.  Then I want to have a canvas that will respond to my mouse clicks and drags to draw lines with arrows on the end.

What objects would you use such as canvas, rectangle, Border, ellipse...and in what zorder would you place them? 

Best Regards,

Trex 

how to use async in WPF - desktop app

How to use RegisterName on a custom class?

$
0
0

Goal: To register a name for animation.

Problem: I am forced to inherit.

Workaround: To use a reference object itself to register it.

Questions:

1. What is a better way?

2. Is workaround reliable?

Code:

    class Class1
    {
        Class1()
        {
            //RegisterName // Doesn't exist

            Ellipse ellipse = new Ellipse();
            ellipse.RegisterName("name", ellipse); // Exists
        }
    }

WPF: How to set how much animation changes value?

$
0
0

Questions:

1. How to animate a property by adding a specific value?

2. What is a default add value?

Note: The DoubleAnimation and Storyboard classes are used.

Example: 0 to 10 by 5 = 0 + 5 + 5 = 10

WPF: How to play animation in reverse?

$
0
0

How to play animation back in reverse at any given point by the MouseDown event?

Note:

1. I don't wanna play animation back from the end.

2. I wanna play animation back from the current state.

3. It would be better to do without creating additional Storyboard or ThicknessAnimation.

Code:

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

            this.Loaded += MainWindow_Loaded;
        }

        Line line;

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Canvas canvas = new Canvas();
            canvas.Background = Brushes.Black;
            this.Content = canvas;

            line = new Line();
            line.Stroke = Brushes.White;
            line.X1 = 0;
            line.Y1 = 0;
            line.X2 = 100;
            line.Y2 = 100;

            canvas.Children.Add(line);

            Animation();
        }

        private void Animation()
        {
            ThicknessAnimation ta = new ThicknessAnimation();
            ta.Duration = TimeSpan.FromSeconds(1);
            ta.From = new Thickness(0, 0, 0, 0);
            ta.To = new Thickness(100, 100, 0, 0);
            ta.RepeatBehavior = RepeatBehavior.Forever;

            Storyboard sb = new Storyboard();
            Storyboard.SetTarget(ta, line);
            Storyboard.SetTargetProperty(ta, new PropertyPath(Line.MarginProperty));
            sb.Children.Add(ta);
            sb.Begin();

            this.MouseDown += delegate
            {
                // Play Back
            };
        }
    }

WPF ContextMenu Binding multilevel items.

$
0
0

Hi All,

I faced an binding issue regarding ContextMenu. My ContextMenu looks like:

MenuItem1

MenuItem2

MenuItem3

OthersMenuItem

OtherMenuItem1

OtherMenuItem2

OtherMenuItem3

How to create binding source object, and how to binding the source to ContextMenu?

Thanks for your help.

Advanced text formatting examples

$
0
0
I'm working on formatted text editor via TextFormatter. I've downloaded the SDK example (https://msdn.microsoft.com/en-us/library/vstudio/ms771407%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396) to understand how this API works. But the implementation of TextSource in this example is too simplistic: it allows to change formatting only of entire text, but I need to have possibility of editing text fragments. I couldn't find any other examples of using TextFormatter (and TextSource implementation). Can somebody give some code samples?

Any help would be much appreciated!

WPF Menu Item Binding and Add Click event to Menu Item.

$
0
0

Hi All,

I have created a custom Menu like ComboBox, Please check this thread.

https://social.msdn.microsoft.com/Forums/vstudio/en-US/802708ad-2f18-47f1-a404-cdbed2caa815

The screenshot like below,

It looks like a multi level ComboBox, But it's a Menu.

This is a Custom WPF Menu Control. My issue is how to binding the data source to MenuItem and how to add MenuItem Click event for each items.

My Data Source class like this,

public class MItem { public string Name{get;set;}

// Binding to the children. public ICollection<MItem> Items{get;set;} }

Thanks a lot.

Prism 5.0 communication between user controls

$
0
0
namespace xxxx.yyyy.ViewModels
{
    class OrderDetailComboModalView : ViewModel
    {
        #region Item Sources

        public ObservableCollection<OrderBooking> OrderList { get; set; }
        public ObservableCollection<Buyer> BuyerList { get; set; }
        #endregion

        #region Binding Examples

        // Property backing fields.
        string selectedOrderBookingCode;
        string selectedOrderBookingCode1;
        string selectedOrderBookingCode2;
        string selectedBuyerCode;


        /// <summary>
        /// Gets or sets the shipping source country.
        /// </summary>
        public string SelectedOrderBookingCode
        {
            get { return this.selectedOrderBookingCode; }
            set
            {
                this.selectedOrderBookingCode = value;
                this.selectedOrderBookingCode1 = value;
                this.selectedOrderBookingCode2 = value;
                this.NotifyPropertyChanged("SelectedOrderBookingCode1");
                this.NotifyPropertyChanged("SelectedOrderBookingCode2");
                this.NotifyPropertyChanged("SelectedOrderBookingCode");

                if (this.selectedOrderBookingCode.Length > 8)
                {
                    this.selectedBuyerCode = this.selectedOrderBookingCode.Substring(6, 2);
                    this.NotifyPropertyChanged("SelectedBuyerCode");
                }
            }
        }

        public string SelectedOrderBookingCode1
        {
            get { return this.selectedOrderBookingCode1; }
            set
            {
                this.selectedOrderBookingCode1 = value;
                this.NotifyPropertyChanged("SelectedOrderBookingCode1");
            }
        }

        public string SelectedOrderBookingCode2
        {
            get { return this.selectedOrderBookingCode2; }
            set
            {
                this.selectedOrderBookingCode2 = value;
                this.NotifyPropertyChanged("SelectedOrderBookingCode2");
            }
        }



        public string SelectedBuyerCode
        {
            get { return this.selectedBuyerCode; }
            set
            {
                this.selectedBuyerCode = value;
                this.NotifyPropertyChanged("SelectedBuyerCode");
            }
        }


        #region Constructors

        public OrderDetailComboModalView()
        {
            // Instantiate our item sources.
            this.OrderList = new ObservableCollection<OrderBooking>();
            this.BuyerList = new ObservableCollection<Buyer>();

            // Simulate data retrieval.
            this.PopulateBookingOrder();
            this.PopulateBuyer();
        }

        #endregion

        #region Simulated Data-Retrieval Methods

        /// <summary>
        /// Simulate the population of data.  In reality this method would most likely be retrieving data from a database, web service, config file, etc.
        /// </summary>
        public void PopulateBookingOrder()
        {
            // Simulate the population of the Countries ObservableCollection.


            OrderList = Populate.PopulateBookingOrder();
            this.SelectedOrderBookingCode = "-1";
            this.NotifyPropertyChanged("SelectedOrderBookingCode");




        }
        public void PopulateBuyer()
        {
            // Simulate the population of the Countries ObservableCollection.
            BuyerList = Populate.PopulateBuyer();
            this.SelectedBuyerCode = "-1";
            this.NotifyPropertyChanged("SelectedBuyerCode");



        }
        #endregion
    }
}


Hi I am relatively new to wpf and in particularly prism or more loosely MVVM. In-fact I may be using Prism at higher level such as navigation via ribbon etc. But at lower level particularly inter-communication between UserControls I have this requirement

Where I have ComboBox => OrderBooking when I select a value  (from Tab1 => UserControl1) It should select same orderNo

in (Tab2 => UserControl2) both populated from same data.

This part repeated in all userControls:-

========================

             xmlns:ViewModels="clr-namespace:xxx.yyy.ViewModels"><UserControl.DataContext><ViewModels:OrderDetailComboModalView /></UserControl.DataContext>

Tab1=>UserControl1

<ComboBox Text="" Name="cmbOrderBookingNo"
                    ItemsSource="{Binding OrderList, Mode=OneWay}"
                    DisplayMemberPath="Name"
                    SelectedValue="{Binding SelectedOrderBookingCode}"
                    SelectedValuePath="Code"


Tab2=>UserControl2:-

==============

<ComboBox Text="" Name="cmbOrderBookingNo"
                    ItemsSource="{Binding OrderList, Mode=OneWay}"
                    DisplayMemberPath="Name"
                    SelectedValue="{Binding SelectedOrderBookingCode1}"
                    SelectedValuePath="Code"

Both Combos are populated ok

===================

BuyerCombo is also populated according to selection Tab1(Both these combos reside in the same Control -> UserControl1)

But When I select OrderBooking Combo in tab1 the same selection does not happen in OrderBooking Combo in UserControl in Tab2

Please does anybody what the problem is?

<orderbooking><buyer><orderbooking><buyer></buyer></orderbooking></buyer></orderbooking>

Text Formatter throws ArgumentOutOfRangeException

$
0
0

Hello!

While working with Text Formatter API I ran into some problems and need help.

I have a LinkedList of text runs (I've created Run class, which has a Text property for storing string of text and a bunch of properties, which define text formatting options). I've also implemented my CustomTextSource class (derived from TextSource). The GetTextRun method implementation:

public override TextRun GetTextRun(int textSourceCharacterIndex)
        {
            Run run = Document.Runs.ToList().Find(x => x.Contains(textSourceCharacterIndex));
            if (run == null)
            {
                return new TextEndOfParagraph(1);
            }

            if (run.Length == 1 && run.Text.ToString()[0] == '\n')
            {
                return new TextEndOfLine(1);
            }

            return new TextCharacters(run.Text.ToString(),
                    run.Start, run.Length,
                    new GenericTextRunProperties(run.Formatting));
        }

where "Contains" is a method of Run class:

public bool Contains(int index)
        {
            return (Start <= index) && ((Start + Length) > index);
        }

"Start" and "Length" properties are just integers, that store the beginnig and length of the text run.

The problem is that in some cases the GetTextRun method throws an ArgumentOutOfRangeException in the last return statement with the message: "Parameter's value can't be greater than [number]. Parameter's name: offsetToFirstChar".
For example, when the text store has a character which represents a new line (new line character stores in separate run) and once Text Formatter takes the span with this character and then tries to take next run (let's call this run "RunAfterNewLine") the [number] in the exception message is equals to (RunAfterNewLine.Length - 1).

So can anyone explain me why it's happens and how to fix it?
Any help would be much appreciated!






Viewing all 18858 articles
Browse latest View live


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