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

Conditional Storyboard Animation

$
0
0

Hi,

So this one is driving me crazy.

I have a small "notification" icon to display the form status. Some of the status require the image to blink, some don't.

The following code kinda "works"

<Rectangle Width="40" Margin="0,0,0,0" x:Name="StatusImage"><Rectangle.Fill><VisualBrush Visual="{Binding Status.Image}" Stretch="None" /></Rectangle.Fill><Rectangle.Style><Style TargetType="Rectangle"><Style.Triggers><DataTrigger Binding="{Binding Status.Blink, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Value="True"><DataTrigger.EnterActions><BeginStoryboard><Storyboard><DoubleAnimation RepeatBehavior="Forever"
                                                                Storyboard.TargetProperty="Opacity"
                                                                From="1.0" To="0.0" Duration="0:0:1"
                                                                AutoReverse="True" ></DoubleAnimation></Storyboard></BeginStoryboard></DataTrigger.EnterActions></DataTrigger></Style.Triggers></Style></Rectangle.Style></Rectangle>

This makes the image blink when Status.Blink is true. But once this one is triggered it never stops no matter if Status.Blink is updated. I suppose i have to stop the animation somehow.

So i tried adding another trigger:

<DataTrigger Binding="{Binding Status.Blink, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Value="False"><DataTrigger.EnterActions><BeginStoryboard><Storyboard><DoubleAnimation RepeatBehavior="1x"
                                                                    Storyboard.TargetProperty="Opacity"
                                                                    From="0.0" To="1.0" Duration="0:0:1"
                                                                    AutoReverse="False" ></DoubleAnimation></Storyboard></BeginStoryboard></DataTrigger.EnterActions></DataTrigger>

But now i only have this animation. Seems to work either one or the other, not both.

Being my first time with Animations i'm most likely doing some stupid newbie error.



Application suddenly very slow in debug mode?

$
0
0

I have a WPF desktop application with 10 or so projects. I am using Visual Studio 10.0 SP1. All of a sudden, it has become extremely slow in debug mode - to the point that I can not even debug it.

The same application runs just fine in debug mode on another pc where I am using Visual Studio 2013 Express. I am using SVN to keep the two copies in sync. No new software or windows update has been installed. Even nothing material has changed in the code.

I looked at the VS debug options on both machines and there is no major difference - using default settings.

Any idea what may be wrong? What should I look for?

Thanks.

Binding resource to a string property in view model!

$
0
0

Hi Everyone,

In my project I a build a ResourceDictionary on the fly which contains language translation stuff. For a given key it returns me the value (depending on current set language).

For example if the language I set is English then the ResourceDictionary contains:

<Node Key=Name>

Name

</Node>

Now I have bound this to XAML view correctly using dynamic property like:

Content="{DynamicResource Name}"

and in code behind, in some cases where I build the menu on the fly, I have this in view model:

 var myMenu= new MyMenuItem
            {
               ...
                Header = Application.Current.GetResource("Name"),
               ...
            };

which works fine.

But as you can see the problem is that I have to execute this piece of code in the view model every time I change the language. So I am using a LanguageChange event which triggers this piece of code.

I want to remove this event and make it work just like it work in the XAML. 

So is there anyway I can just execute the code above once, and every time the language changes the values are reflected everywhere. I think I can turn all such strings in ViewModel to DependencyProperty and then bind them to the resource in the code behind, but there are just too many of them so I am looking for a quicker way.

Thanks.


Please Mark as Answered If this answers your question OrUnMark as Answered if it did not.
Happy to Help :)
My Site


Thread Print problem

$
0
0

I have an application which opens some Windows in a new Thread. I have a custom build Menu with a print command.

The problem I'm facing is that when I want to print from the threaded Window I get a System.Invalidoperationexception:
"The calling thread cannot access this object because a different thread owns it"

I think the issue is that the visual is in the threaded window, but the Printdialog gets executed on main thread, as I understand this ???

Sample App for testing and review at:

Sample

public static void StartPrint(Window win, string name)
        {
            FrameworkElement vs = (FrameworkElement)ControlUtility.FindVisualChildByName<Grid>(win, "MainGrid");

//Getting the error here

            Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    PrintDialog pd = new PrintDialog();

                    if (pd.ShowDialog() == true)
                    {
                        pd.PrintVisual(vs, name);
                    }
                }));
        }

c++ to c# conversion- struct

$
0
0

In C++ struct and member name can be similar. How to achive that in C#.

C++:

 

typedef struct {
  unsigned  short  Unique_Word;    
  unsigned short   Shop_Mode_Request;
  unsigned short   Checkword;
}Shop_Mode_Request;

C#:

public struct Shop_Mode_Request
{
  public ushort  Unique_Word;
  public ushort  Shop_Mode_Request;
  public ushort  Checkword;
};

This is throwing error.

FlowDocumentScrollViewer inside Grid

$
0
0

Hi,

I have a problem with the FlowDocumentScrollViewer control inside a Grid with one ColumnDefinition having Width set to Auto. Here is a simple example:

<Grid><Grid.ColumnDefinitions><ColumnDefinition Width="auto"/></Grid.ColumnDefinitions><FlowDocumentScrollViewer VerticalScrollBarVisibility="Disabled" ><FlowDocument PagePadding="0"><BlockUIContainer><Border Background="Red" Width="800" Height="50"/></BlockUIContainer></FlowDocument></FlowDocumentScrollViewer></Grid>

The Border inside the BlockUIContainer is always clipped to 500px. Is there a reason for limiting the size of the content in this case?

Thank you in advance for any help.

How to to slect opened window on specific monitor in multi monitor system

$
0
0

Hi,

I have four monitor attached to my box. I have already implemented code to move selected window on given monitor on hokey. e.g window1 is opened on monitor one and if that window is active then using hot key i am moving it to specified monitor like Ctrl+1 move to monitor 1, Ctrl + 2 move to monitor 2 ..so on..

Now i want to implement another hot key, which will activate the window opened on specified monitor. means if i press Alt +1 then if any window is on the monitor should get active and if i press alt + 3 then if any window is there on monitor 3 should get activated.So how to achieve this?

H


Vipul Mistry Sr. Embedded Engineer www.eInfochips.com

Specified cast is not valid when trying to cast public enum to column headers of DataGrid in the code behind

$
0
0
Hello,

I have defind a public enum that consists of a list of DataGrid column headers as follows, specified the XAML code behind:

       public enum ColumnHeaders
       {
            address1Header,
            address2Header,
            address3Header,
            countyHeader,
            postCodeHeader,
            townHeader,
            telHeader,
            faxHeader,
            emailHeader
        }

I cast the ColumnHeaders to the currentCell.Column.Header object in the following method:

        private void Cell_TextChanged(object sender, TextChangedEventArgs e)
        {
            DataGridCellInfo currentCell = dataGrid.CurrentCell;
            if (currentCell.Column == null)
                return;

            ColumnHeaders columnHeader = (ColumnHeaders)currentCell.Column.Header;

            switch (columnHeader)
            {
                case ColumnHeaders.address1Header:
                    ... some code ...
                    break;

                case ColumnHeaders.address2Header:
                     ... some code ...
                    break;
}

The code compiles successfully.  However, at the run time, it fails and generates the following error message:

System.InvalidCastException was unhandled
  HResult=-2147467262
  Message=Specified cast is not valid.

I can cast the object currentCell.Column.Header to a string, no problem.

Any ideas?

Thanks.


Abbas



Unable to solve Datagrid solution

$
0
0

I am trying to rewrite a Windows form program to WPF. The top image is the original program that I am trying to recreate in WPF. For the moment I have a test program that I am using to try and achieve what I want.

To create the columns I use code behind : 

            foreach (DateTime dt in EachDay(dtpStartDate.SelectedDate.Value, dtpEndDate.SelectedDate.Value))
            {
                DataGridTextColumn col = new DataGridTextColumn();
                col.Header = string.Format("{0:dd/MM}", dt);
                //col.Binding = new Binding("??????");
                MyDataGrid.Columns.Add(col);
            }

        public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
        {
            for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
                yield return day;
        }

and fill the datagrid rowheader with my data from database. 

                using (MaterialEntities me = new MaterialEntities())
                {
                    var listOfItems = from i in me.items
                                      where !i.isReturned
                                      where i.categoryID == 24
                                      select new Planner
                                      {
                                          Name = i.name,
                                          ID = i.itemID
                                      };

                    MyDataGrid.ItemsSource = listOfItems.ToList();
                }

To find out which item listed on the left is reserved for a mission between the dates that the columns represent and change background colour accordingly I thought of using a multi value converter. In the conveter I will write the code needed to return the ifo from the database tables. I have got as far as using a value converter to change the background cell

    class FreightMissionConverter : IValueConverter
    {
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int temp = (int)value;

            if (temp == 462)
            {
                return Brushes.Blue;
            }
            return Brushes.Yellow;
        }
}
<DataGrid x:Name="MyDataGrid" AutoGenerateColumns="False" Grid.Row="1" SelectedValuePath="ID"><DataGrid.Resources><local:FreightMissionConverter x:Key="FreightMissionConverter" /><Style TargetType="{x:Type DataGridCell}"><Setter Property="Background" Value="{Binding Path=ID, Converter={StaticResource FreightMissionConverter}}"></Setter></Style></DataGrid.Resources><DataGrid.RowHeaderStyle><Style TargetType="DataGridRowHeader"><Setter Property="Content" Value="{Binding Name}" /></Style></DataGrid.RowHeaderStyle></DataGrid>

but I will need a multi value converter to bring in the item and the date (column header). I believe that column headers aren't bindable. Perhaps there is another way round this. My other difficulty is filling the cell with the missions' number as I can only return the colour for the cell's background.  Perhaps the only solution is to run through the datagrid in code only as I did with the Winforms program? 

Thanks for any help.


:-( Still trying to program

Problem With Rebinding Saved User Control

$
0
0

I am having a problem rebinding a Loaded  WPF User control the target control property does not update , The Control is binding correctly when I first create the control but does not bind After the Control is loaded after being saved. I have understood from a previous post that all Bindings are lost when sterilization takes place. However since I have decided to bind in code I would expect the target to display the source value. Can anyone explain why this is not happening.

UI XAML file  I am only trying to get the lblDescription to display source data at the moment. I  tried multiple ways but none seem to work. The XMLSave function is from code taken from (http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part

<base:BaseUserControl  x:Class="WPFControlLibrary.Controls.HorizontalGauge"
             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:base="clr-namespace:WPFControlLibrary.Base"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="300"><Grid><Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><Grid.RowDefinitions><RowDefinition Height="25"/><RowDefinition Height="*"/><RowDefinition Height="30"/></Grid.RowDefinitions><Label  Tag="lblDescription"    Content="Not Set" HorizontalAlignment="Center"  Grid.Row="2" VerticalAlignment="Stretch" FontWeight="Bold" FontSize="14"/><Grid Grid.Row="0" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" ><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Label Tag="lblleftboundary"  Grid.Column="0" Content="{Binding MinValueString}" HorizontalAlignment="Left" FontWeight="Bold"
                      /><Label Tag="lblMiddleBoundary" Grid.Column="1" Content="50" HorizontalAlignment="Center" FontWeight="Bold"/><Label  Tag="lblUpperBoundary"  Grid.Column="2" Content="{Binding MaxValueString}" HorizontalAlignment="Right" FontWeight="Bold"/></Grid><ProgressBar HorizontalAlignment="Stretch" Grid.Row="1"  VerticalAlignment="Stretch" BorderThickness="3" Cursor="Arrow" Foreground="{Binding ProgressBarForground}" Value="{Binding ProgressBarValue}" Background="Black" Maximum="{Binding maxValue}" Minimum="{Binding minValue}" ><ProgressBar.BorderBrush><LinearGradientBrush EndPoint="0,1" StartPoint="0,0"><GradientStop Color="#FFB2B2B2" Offset="0"/><GradientStop Color="#FF5F7A9B" Offset="1"/></LinearGradientBrush></ProgressBar.BorderBrush></ProgressBar></Grid></Grid></base:BaseUserControl>

And here is the Code behind for the Control (only the label bit is important)

using System.Windows.Media;

namespace WPFControlLibrary.Controls
{
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;

    using Dan.monitor.Common;

    using WPFControlLibrary.Base;



    [MonitorControl(true)]

    public partial class HorizontalGauge : BaseUserControl, IMonitorControl
    {
        private ProgressBar hProgressBar;
        private Dictionary<string, Label> labels = new Dictionary<string, Label>();
        private float _progressBarValue;
        private SolidColorBrush progressBarForground;
        public HorizontalGauge()
        {
            InitializeComponent();
            RebindControls();
            NewValueReceived+=HorizontalGauge_NewValueReceived;
        }


        private void RebindControls()
        {
            var grid = this.FindChild<Grid>();
            hProgressBar = this.FindChild<ProgressBar>();
            foreach (var child in grid.FindChildren<Label>(x=> !string.IsNullOrEmpty(x.Tag.ToString())))
            {
                labels.Add(child.Tag.ToString(),child);
            }

            Binding descriptionBinding = new Binding("Description");
            descriptionBinding.Source = this;
            descriptionBinding.Mode = BindingMode.OneWay;
            BindingOperations.SetBinding(labels["lblDescription"], Label.ContentProperty, descriptionBinding);
        }

        private void HorizontalGauge_NewValueReceived(NewMetricEventValue e)
        {
            if (e.Value != null)
            {
                ProgressBarValue = (float)e.Value.Raw;
            }
        }

        public float ProgressBarValue
        {
            get
            {
                return this._progressBarValue;
            }
            set
            {
                this._progressBarValue = value;
                CheckColorStatus(value);
                this.CallPropertyChange("ProgressBarValue");
            }
        }

        public SolidColorBrush ProgressBarForground
        {
            get
            {
                return this.progressBarForground;
            }
            set
            {
                if (this.progressBarForground != value) this.progressBarForground = value;
                this.CallPropertyChange("ProgressBarForground");
            }
        }

        private void CheckColorStatus(float value)
        {
                if (value <= Ok)
                {
                    ProgressBarForground = new SolidColorBrush(OkColor);
                }

                if (value > Warn)
                {
                    ProgressBarForground = new SolidColorBrush(WarnColor);
                }
                if (value >= Alert)
                {
                    ProgressBarForground = new SolidColorBrush(AlertColor);
                }
        }
    }
}

And Here is the BaseClass (Reduced)

// --------------------------------------------------------------------------------------------------------------------
//
//
// </copyright>
// <summary>
//   The base user control.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WPFControlLibrary.Base
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;

    using Dan.monitor.Common;
    using Dan.monitor.Common.Dan.Common.Messages;

    /// <summary>
    /// The base user control.
    /// </summary>
    public abstract class BaseUserControl : UserControl, INotifyPropertyChanged
    {
        private float alert;

        private Color alertColor;

        private string description;

        private bool emailOnAlert;

        private EmailMessage emailReceipient;

        private IMetricValue value;

        private string monitoringEvent;

        private float ok;

        private Color okColor;

        private float warn;

        private Color warnColor;

        private bool autoMin;

        private bool autoMax;

        private float maxValue;

        private float minValue;

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseUserControl"/> class.
        /// </summary>
        public BaseUserControl()
        {
            this.MouseDoubleClick += this.UserControl_MouseDoubleClick;
        }

        #endregion

        #region Public Events

        /// <summary>
        /// The double clicked.
        /// </summary>
        public event EventHandler DoubleClicked;

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets the alert.
        /// </summary>
        public float Alert
        {
            get
            {
                return this.alert;
            }
            set
            {
                this.alert = value;
            }
        }

        /// <summary>
        /// Gets or sets the alert color.
        /// </summary>
        public Color AlertColor
        {
            get
            {
                return this.alertColor;
            }
            set
            {
                this.alertColor = value;
            }
        }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        public  string Description
        {
            get
            {
                return this.description;
            }
            set
            {
                if (this.description != value)
                {
                    this.description = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("Description"));
                }
            }

        }

        /// <summary>
        /// Gets or sets a value indicating whether email on alert.
        /// </summary>
        public virtual bool EmailOnAlert
        {
            get
            {
                return this.emailOnAlert;
            }
            set
            {
                this.emailOnAlert = value;
            }
        }

        /// <summary>
        /// Gets or sets the email receipient.
        /// </summary>
        public virtual EmailMessage EmailReceipient
        {
            get
            {
                return this.emailReceipient;
            }
            set
            {
                this.emailReceipient = value;
            }
        }

        public virtual IMetricValue Value
        {
            get
            {
                return this.value;
            }
            set
            {
                this.value = value;
                NewValueReceived(new NewMetricEventValue(value));

            }
        }

        /// <summary>
        /// Gets or sets the monitoring event.
        /// </summary>
        public string MonitoringEvent
        {
            get
            {
                return this.monitoringEvent;
            }
            set
            {
                this.monitoringEvent = value;
            }
        }

        /// <summary>
        /// Gets or sets the ok.
        /// </summary>
        public virtual float Ok
        {
            get
            {
                return this.ok;
            }
            set
            {
                this.ok = value;
            }
        }

        /// <summary>
        /// Gets or sets the ok color.
        /// </summary>
        public virtual Color OkColor
        {
            get
            {
                return this.okColor;
            }
            set
            {
                this.okColor = value;
            }
        }

        /// <summary>
        /// Gets or sets the warn.
        /// </summary>
        public virtual float Warn
        {
            get
            {
                return this.warn;
            }
            set
            {
                this.warn = value;
            }
        }

        /// <summary>
        /// Gets or sets the warn color.
        /// </summary>
        public virtual Color WarnColor
        {
            get
            {
                return this.warnColor;
            }
            set
            {
                this.warnColor = value;
            }
        }

        public virtual bool AutoMin
        {
            get
            {
                return this.autoMin;
            }
            set
            {
                this.autoMin = value;
            }
        }

        public virtual bool AutoMax
        {
            get
            {
                return this.autoMax;
            }
            set
            {
                this.autoMax = value;
            }
        }

        public virtual float MaxValue
        {
            get
            {
                return this.maxValue;
            }
            set
            {
                this.maxValue = value;
                MaxValueString = value.ToString();
                PropertyChanged(this, new PropertyChangedEventArgs("maxValue"));
            }
        }

        public virtual float MinValue
        {
            get
            {
                return this.minValue;
            }
            set
            {
                this.minValue = value;
                MinValueString = value.ToString();
                PropertyChanged(this, new PropertyChangedEventArgs("minValue"));
            }
        }

        public string MinValueString
        {
            get
            {
                return this.minValueString;
            }
            set
            {
                this.minValueString = value;
                PropertyChanged(this, new PropertyChangedEventArgs("MinValueString"));
            }
        }


        public string MaxValueString
        {
            get
            {
                return this.maxValueString;
            }
            set
            {
                this.maxValueString = value;
                PropertyChanged(this, new PropertyChangedEventArgs("MaxValueString"));
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// The user control_ mouse double click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void UserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.DoubleClicked(sender, e);
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public delegate void NewValueReceivedEventHandler(NewMetricEventValue e);
        public event NewValueReceivedEventHandler NewValueReceived = delegate { };

        private string minValueString;
        private string maxValueString;


        void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }


        internal void CallPropertyChange(string propertyName)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }
    }

    public class NewMetricEventValue
    {
        public IMetricValue Value;
        public NewMetricEventValue(IMetricValue e)
        {
            Value = e;

        }
    }


}


Developer of bits

WPF Window is not Opening from IIS

$
0
0

I have created "Web Site Project", in that project I have added "ASMX Web Service". I am opening WPF application using Web Service call.

Here is the sample:

[WebMethod]
public void strt()
{
  Process.Start(@"C:\application.exe");
}

My web service URL is like this:

"localhost:12345\WebSite.asmx

Now, whenever I run this web service and call this method from Visual Studio:

"WPF starts running and opens the WPF start Windows"

Then I have configure this Web Site to IIS and bind to Port 82. Now my project URL is like this:

localhost:82\WebSite.asmx

I have configured all things right. I am able to Browse to my Directory from IIS.

Now when I go to "ASMX Web Service" and call "Web Service Method" from IIS, The method gets called and also "WPF application" starts, but main problem is

"WPF is running in background, not opening the start Windows of WPF".

How to solve this issue? I have to configure this project in IIS and show Star Up Window from IIS.

Any help would be greatly appreciated. Thanks!!

How to binding and change VM property value when DataTrigger?

$
0
0

Hi all,

Please see the below code. The current work is when mouse over myButton then set textbox value as 3. Then binding this value to ViewModel property, at this time, the new value of ViewModel property also be 3.

The textbox just like a bridge. Can I remove this bridge and change the VM property directly when <setter..... in myTrigger style? thanks.

<Style x:Key="myTrigger" TargetType="TextBox"><Style.Triggers><DataTrigger Binding="{Binding IsMouseOver, ElementName=myButton}" Value="True"><Setter Property="Text" Value="3"></Setter></DataTrigger></Style.Triggers></Style>

What version of Visual Studio should I upgrade to?

$
0
0

I am using Visual Studio 10 Professional in my Company. There are only two people using it but our WPF application is vast and we also have WCF services. The OS is Windows Server 2008 R2.

What version of Visual Studio should I upgrade to?

Thanks.

WPF Threading Backgroundworker issue

$
0
0

I have two different background thread who does similar thing but at different time in my WPF application. both are right now independent background worker.

1) first thread runs when you launch application, it downloads all images from connected printer to PC location.

2) second thread does the same thing  when use click on some link in my application. 

As both worker are independent, even though first thread's downloading process are still running, if user click on link the second thread start their work too 

What I would like to do is, when user click on 2nd thread, is there any way I will know about status of first thread ? I mean if i know that first thread is doing it's work then I don't want to even start second thread. I need only second thread when first one got cancelled by some other reason.

I heard about Mutex but I dont know how it works. Pls share ur idea and some example if you know how to handle this.

Thanks

Dee 


unit test for email field

$
0
0

Hi All.

I'm using VS 2012. I would like to create my first unit test for form with email field entry. I validate that field using Regex. But how create unit test for email field?

Thanks.



Why this binding add 1 extra pixel everytime I move the slider to a tick position?

$
0
0
  private void slider_paragraph_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            double Ratio = slider_paragraph.Value / (slider_paragraph.Maximum - slider_paragraph.Minimum); // Porcentagem do thumb na tela
            double ThumbPosition = Ratio * slider_paragraph.ActualWidth; //posição absoluta




            rtb1.Focus();

            rtb1.Selection.ApplyPropertyValue(Paragraph.TextIndentProperty, ThumbPosition);

        }

Its ok at first tick. The thumb is aligned with text indent. But after the second one it starts to add 1 pixel everytime I increase the slider value. In the last tick the indentation is about 10 pixels ahead of thumb.

Thanks.

Update button in my sample project not firing

$
0
0

My sample project (VS2012) is about working with ICommand(s) and contains two textboxes, a button, and a ListView, a Person class (model), a PersonViewModel class, a RelayCommand Class, and a Person.xaml view.  On launching the project, I binded the ListView to an ObservableCollection property in the ViewModel, and I populate this ObservableCollection in the ViewModel constructor with 2 Name/Address items (of type Person).  The objective is that when I click a row in the ListView, the Name item will appear in one textbox and the Address item in the next textbox.  If I edit the textboxes, I want to click the Update button to update the changed items in the ListView. 

Right now the textboxes are bound to the ListView, so when I click a row on the ListView the respective values automatically appear in the textboxes, and the ListView is bound to a Name property and Address property in the Person class (which contains OnPropertyChanged events).  So when I edit a textbox and click on the other textbox, the Listview Updates automatically.  So the Update button is not even required in the scenario.

I have an Update Command in the ViewModel which I binded the Update button to, but it does not appear to be firing.  I placed some break points in the code for the Update Command, but code execution never stops in the Update command after I click the Update button.  However, the RelayCommand appears to be getting invoked (I write "testing" to console in the RelayCommand Execute event) when I click the Update button

How do I get the Update command to fire (in the code below) ?  If I comment out the OnPropertyChanged event in the Person (Model) class -- then the ListView does not automatically update after I edit the textboxes.  But the Update button does not fire.  What code changes do I need to make so that the edits get updated in the ListView only after I click the Update button?  How do I get the Update button to fire?  This is purely an exercise for me to gain understanding of MVVM workings.

Person.xaml

<Window x:Class="myICommandSample.View.Person"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:myICommandSample.ViewModel"
        Title="Person" Height="300" Width="300"><Window.DataContext><vm:PersonViewModel/></Window.DataContext><Grid><Grid.RowDefinitions><RowDefinition Height="auto"/><RowDefinition Height="auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="100"></ColumnDefinition><ColumnDefinition Width="*"></ColumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="auto"></RowDefinition><RowDefinition Height="auto"></RowDefinition></Grid.RowDefinitions><Label x:Name="lblName" Content="Name" Grid.Row="0" Grid.Column="0" VerticalAlignment="Top"></Label><TextBox x:Name="txtName" Grid.Row="0" Grid.Column="1" VerticalAlignment="Top" Text="{Binding ElementName=lstPerson, Path=SelectedItem.Name}"></TextBox><Label x:Name="lblAddress" Content="Address" Grid.Row="1" Grid.Column="0" VerticalAlignment="Top"></Label><TextBox x:Name="txtAddress" Grid.Row="1" Grid.Column="1" VerticalAlignment="Top" Text="{Binding ElementName=lstPerson, Path=SelectedItem.Address}"></TextBox></Grid><Button x:Name="btnUpdate" Width="100" Height="20" HorizontalAlignment="Center" Grid.Row="1" Content="Update"
                Command="{Binding UpdateCommand}" CommandParameter="{Binding ElementName=lstPerson, Path=SelectedItem.Address}"></Button><ListView x:Name="lstPerson" Grid.Row="2" ItemsSource="{Binding Persons}"><ListView.View><GridView><GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" /><GridViewColumn Header="Address" Width="200" DisplayMemberBinding="{Binding Address}"/></GridView></ListView.View></ListView></Grid></Window>

Person.cs (Model)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace myICommandSample.Model
{
    public class Person : INotifyPropertyChanged
    {
        private string name;
        private string address;

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

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
        public string Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
                OnPropertyChanged("Address");
            }
        }
    }
}

PersonViewModel.cs (PersonViewModel class and RelayCommand class)

using System; using System.Collections.Generic; using System.Collections; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using myICommandSample.Model; namespace myICommandSample.ViewModel { public class PersonViewModel { private ObservableCollection<Person> _personList; public PersonViewModel() { _personList = new ObservableCollection<Person>() { new Person(){Name="Steve", Address="NY"}, new Person(){Name="John",Address="CA"} }; } public ObservableCollection<Person> Persons { get { return _personList; } set { _personList = value; } } private ICommand mUpdater; public ICommand UpdateCommand { get { //--nothing gets fired in here if (mUpdater == null) mUpdater = new RelayCommand(); return mUpdater; } set { mUpdater = value; } } }

//------------------------------------------------------ class RelayCommand : ICommand { public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { Console.WriteLine("testing"); } } }


Rich P




Unable to cast object in designer

$
0
0

I have a custom control that inherits from ToggleButton. Inside the button, I'm catching the VisualStateGroup.CurrentStateChanging event in order to change the color of a DrawingBrush. The code is similar to that I use elsewhere, but I'm using resources instead of dependency properties:

    Private Sub StateChanging(sender As Object, e As VisualStateChangedEventArgs)
        Dim iconEl As Rectangle = CType(GetTemplateChild("IconEl"), Rectangle)
        Dim bdr As Border = CType(GetTemplateChild("LayoutRoot"), Border)
        Dim fore As SolidColorBrush = Brushes.Transparent
        Dim back As SolidColorBrush = Brushes.Transparent

        Select Case e.NewState.Name
            Case "Normal", "Unchecked"
                fore = CType(FindResource("RectNormalForeground"), SolidColorBrush)
                back = CType(FindResource("RectNormalBackground"), SolidColorBrush)
            Case "MouseOver"
                fore = CType(FindResource("RectHoverForeground"), SolidColorBrush)
                back = CType(FindResource("RectHoverBackground"), SolidColorBrush)
            Case "Pressed", "Checked"
                fore = CType(FindResource("RectPressedForeground"), SolidColorBrush)
                back = CType(FindResource("RectPressedBackground"), SolidColorBrush)
        End Select

        bdr.Background = back

        Me.ButtonIcon = Me.ButtonIcon.CloneCurrentValue()
        Dim paths As DrawingCollection = CType(Me.ButtonIcon.Drawing, DrawingGroup).Children
        For Each i As Drawing In paths
            CType(i, GeometryDrawing).Brush = fore
        Next

    End Sub

Works fine at runtime, and I've stepped through the procedure without error, but in the VS designer I'm getting an error: 'Unable to cast object of type 'MS.Internal.NamedObject' to type of 'System.Windows.Media.SolidColorBrush'

I've looked around on the forums and on StackOverflow, and this problem usually seems to be related to binding, which I'm not doing here. Any idea?


Rebecca M. Riordan

Static Property - Public Class - databinding within the userControl using the static property?

$
0
0
<CheckBox Content="Is partial radiographic"  IsChecked="{Binding IsBVpartialRadioGraph}" Visibility="{Binding IsBV,Source={StaticResource Pi},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BooleanToVisibilityConverter}}"/>
        public static bool IsBV
        {
            get { return _IsBV; }
            set { _IsBV = value;
            if (_IsBV)
                designCode = "BV";
            //Pi pi = new Pi();
            //pi.NotifyPropertyChanged();
            }
        }

I tried different things, but none worked. Initially databinding  is working fine, ie definitely there is a link. I think I need to implement INotifyPropertyChanged interface, since  IsBV is a static property I can't. If I would create a new instance then it's obviously not referring to the same property. 

In this [link] (second reply) it implements a way of doing it, but then I have to declare a private constructor and hence won't be able to define my class in the resources. 

<TabItem.Resources><l:Pi x:Key="Pi"/></TabItem.Resources>

Getting HTML data from webbrowser.document property

$
0
0

When I try to get the WebBrowser.Document HTML property in WPF I am unable to do so, I tried casting the Document property to that of HTMLDocument but there are issues with the COM object.

In winforms it is easy, WebBrowser.Document.Body.OuterHTML, how do I do this in WPF?

Cheers

Pieter

Viewing all 18858 articles
Browse latest View live


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