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

How to get a name from ControlTemplate from different charts?

$
0
0

I have three charts one below the other:

In xaml there is a ControlTemplate:

<ControlTemplate x:Key="ZoomChartTemplate"><Border BorderBrush="Black" BorderThickness="1,0,1,1" Background="Azure"><chartingprimitives:EdgePanel x:Name="ChartArea" ><Border BorderBrush="Black" BorderThickness="1,1,1,1"><Canvas x:Name="c1" Width="Auto" Height="Auto" ></Canvas></Border></chartingprimitives:EdgePanel>

</Border></ControlTemplate>

For every of these three charts i assigned this control template like this:

ControlTemplate C1 = this.Resources["ZoomChartTemplate"] as ControlTemplate;

chart1.Template = C1;

chart2.Template = C1;

Chart3.Template = C1;

When user click on some of those charts, I need to identify which of content is selected, becouse I have to know on which chart user clicked for futher changes. How can I do that?


Loading a 1bpp image into an image control causes a memory issue

$
0
0

Hi friend!

As described in the title I am trying to dispaly an image 14'043 x 9933 (A0 tif file) in an image control.
I also use a zoom and pan functionality to allow better viewing. But that doesn't matter for this specific question.
(But that's why I need to use a writeable bitmap)

However, I created the following code wich generates a byte array, creates a writeable bitmap out of it and sets that bitmap as the source of my image control.

Memory issues occure when setting the writeable bitmap as the source of the control.

//Routine start

 var width = 14043;
 var height = 9933;

 var stride = (width + 7) / 8;
 var pixels = new byte[height * stride];

 for (int i = 0; i < height * stride; i++)
 {
       pixels[i] = 0xAA;
 }

 _writeableBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.BlackWhite, null);
 _writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, stride, 0);
 _writeableBitmap.Freeze();
 return _writeableBitmap;

//Routine end

I would be very thankfull if anyone could provide a working solution :D

Impact on applying ValidationRule

$
0
0

Hello,

I have an "Age" property which is a notified property and it is raised when my date of birth in datepicker changes. That is I am calculating Age depending on the selected date.

Below is my Validation Rule class:

public class DateBirthRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null)
            {
                return new ValidationResult(false, "Please enter a valid date");
            }

            return new ValidationResult(true, null);
        }

    }

I have the following trigger in style:

<Style.Triggers><Trigger Property="Validation.HasError" Value="true"><Setter Property="ToolTip"
        Value="{Binding RelativeSource={RelativeSource Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/></Trigger></Style.Triggers>

Below is the DatePicker in XAML:

<DatePicker  Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" Margin="2,4"  Width="215"  HorizontalAlignment="Left" VerticalAlignment="Center" Style="{StaticResource DatePickerStyle}"><DatePicker.SelectedDate><Binding Mode="TwoWay" Path="DateOfBirth" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True"><Binding.ValidationRules><local:DateBirthRule /></Binding.ValidationRules></Binding></DatePicker.SelectedDate></DatePicker>

Below is the DateOfBirth Property:

public DateTime? DateOfBirth
        {
            get
            {
                return _dateOfBirth;
            }

            set
            {
               _dateOfBirth = value;
                RaisePropertyChanged(() => DateOfBirth);
                RaisePropertyChanged(() => Age);
            }
        }

The issue is that when i delete the value in my datepicker (i.e DateofBirth) the "Set" in the above property does not get called and hence the "Age" property is not raised.

This is because the Validation method in the class DateBirthRule.cs gets hit first the DatOfBirth is validated and it never goes to above DateOfBirth property.

Please suggest how can i handle this and Calculate the Age based on DateOfBirth Change.

Thanks,

Abdi

Timeline in WPF

$
0
0

I'm creating a wpf desktop application, where a time-line is split into time-slots. The user is able to drag GIF images to these time-slots (one GIF per time-slot). The start time of the following time-slot depends upon the end-time of the GIF in the previous time-slot.

Can anyone provide any advice or help on how to approach this? Thanks in advance!

Adorners visible for elements in collapsed expander

$
0
0
I'm having a problem where adorners that adorn elements in an expander are visible when the expander is collapsed (the element is no longer visible). This is pretty easily reproducible. Take any one of the SDK samples that use an adorner, and put the main part of a page in an expander - make sure to mark the expander as IsExpanded=True, otherwise most of them will throw errors (I used the AddRemoveAdorner sample to reproduce it). Is there something special that needs to be done for elements that use adorners and are in an expander? I tried using the AdornerDecorator, but that didn't help.

XamDataGrid columns- MVVM

$
0
0

Hello,

I am writing my app using MVVM pattern.

I have a XamDataGrid and i need to display in it my ViewModels.

I have a collection of VMs so each VM should be a row in the DataGrid. 

Also each VM has a child VM that has collection of VMs. Each such VM contains 3 properties- Field, Value and operator.

I need the DataGrid to have dynamic fields according to the fields i have (in the collection of "small" VMs). each cell will contain the right value from the small VM under the right field . 

The operator value should be displayed in another operator column. All operators are the same for the VMs related to same row in the DataGrid.

Currently i did it using dependency property- i bind the collection of VMs and than build a DataTable with dynamic columns and set is as DataSource of the dataGrid. 

The thing is that it is fine if my DataGrid is read-only. But i need an option to change the DataGrid values . If i will do it with current code (with dependency property) i don't know what VM to change (because the DataGrid cell is not bind to any object). 

How can i still solve this so it will work with binding?

Improper DPI and Resolution Values in WPF Application with DisableDpiAwareness attribute

$
0
0
Hi All,

We had developed a Winforms Application usind .Net Framework 2.0. Currently we started migrating the application to WPF(.Net 4.0).

Hence we have some screens developed using WPF and few unmigrated(2.0/WinForms) screens are hosted using WindowsFormHost in our Application

We have a issue while running the Application in High DPI & Resolution. Meaning that the WPF screens are scaled accordingly with respect to DPI and Resolution whereas the WindowsFormsHost screens are not scaled up properly.

We have raised this issue earlier also and we received a response stating that setting DisableDpiAwareness at AssemblyInfo.cs of Application may resolve this. But with the constraint that developer should take care of scaling the components appropriately.

We have tried applying this DisableDpiAwareness attribute for our application. It worked fine except with the below issues.

We have to calculate the System Resolution and DPI in user's machine. Since we have set the DisableDpiAwareness attribute for Application, we are not getting the correct values in following properties for various values of DPI and Resoltion.

DPI & Resolution Calculation:
-----------------------------
1) var dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static);
var dpiYProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static);

var dpiX = (int)dpiXProperty.GetValue(null, null);
var dpiY = (int)dpiYProperty.GetValue(null, null);

2) SystemInformation.PrimaryMonitorSize;
3) Screen.PrimaryScreen.Bounds

Please let me know how we shall calculate/retrieve the System Resolution in the application with DisableDpiAwareness attribute.

Kindly let me know if you require any information on the same.

Thanks In Advance.
Javithkhan Ayubkhan

System.Windows.Media.Effects.ShaderEffect , ps_3_0, raw texture access w/o filtering and sampling

$
0
0

A custom pixelShader Effect for yuv422 to RGB  isnt flying.  The shader needs to sample with capability like ps_4_0 'Buffer.Load()', without any sample averaging or filtering or mangling of the input texture.

The shader detects even pixel or odd pixel invocation and uses the appropriate uv adjustments to sample the same two input pixels for each even/odd adjacent pair, then uses either Y1 Cr Cb or Y2 Cr Cb to output the even or odd pixel RGB.  (A two element array is defined and the proper even/odd index calculated, to eliminate the conditional path.)   That isn't what is hosing.

What is hosing is, the sampling of the input Gray16 value, sourced from a supplied buffer of Y1 U Y2 V bytes (as two adjacent Gray16 pixels).   The texture is sampled at the two adjacent pixels, the r.channel is used to descale back to 0-65536 for the two adjacent pixels, and then the Y1 Cr or Y2 Cb is calculated from the appropriate MSB or LSB from the adjacent pixels.

What is hosing is, the MSBs are sampled and descaled unmolested, but the LSBs are mangled,  like sampling or filtering.

WPF exposes  RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Unspecified" which I've set on the associated <Image>

The fragment shader sampler_state is set as:

texture Texture;

sampler TextureSampler = sampler_state
{
texture = < Texture > ;
magfilter = POINT;
minfilter = POINT;
mipfilter = POINT;
MinLOD = 0;
MaxLOD = 0;
MipLODBias = 0;
AddressU = clamp;
AddressV = clamp;
};

The input is tex2D sampled, denormalized to 0-65535 and then split into LSB and MSB to recover Y1 Cb (and on adjacent pixel Y2 Cr) 

A test with constant data upstream (every pixel set to 0x4080,  which is laid out in memory as 0x80,0x40,0x80,0x40...  resulted in every sampled LSB == every sampled MSB = 0x40.

The input texture is based on a WriteableBitmap with format Gray16.

the LSBs are either getting mangled in the pipeline/sampling, or the denormalization of the Gray16 and split into MSB and LSB is mangled. 

So my questions are:= 

1] How should a ps_3_0 shader sample an input without sampling or filtering applied(ie, like the intent of ps_4_0 Buffer.Load()) to recover the original 16 bit data value?     float pix16 = floor(tex2D(input,uv).r * 65535)?

2] With the resulting value, what is MSB?    float MSB = floor( pix16/256.0f)?

3] What is LSB?   float LSB = pix16 - 256.0f*MSB?   or similarly, fmod(pix16,256.0f)?

Using VS2013, but the integrated graphics debugger isn't quite flying; won't sample a frame.

Setting up NSight on target system to see if it will provide better diagnostics.



I was born a small child; an infant, really.


ProgressBar.Maximum doesn't work

$
0
0

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication8 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } ProgressBar.Maximum = 20; private void Button_Click(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void Button_Click_1(object sender, RoutedEventArgs e) { } private void ProgressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { } } }

Especially this:

ProgressBar.Maximum = 20;

"Maximum is a property but is used like a type". How do I define it otherwise?

I also tried similiar thing with adding items to Combobox and it didn't work either.
<mytubeelement data="{"bundle":{"label_delimitor":":","percentage":"%","smart_buffer":"Smart Buffer","start_playing_when_buffered":"Start playing when buffered","sound":"Sound","desktop_notification":"Desktop Notification","continuation_on_next_line":"-","loop":"Loop","only_notify":"Only Notify","estimated_time":"Estimated Time","global_preferences":"Global Preferences","no_notification_supported_on_your_browser":"No notification style supported on your browser version","video_buffered":"Video Buffered","buffered":"Buffered","hyphen":"-","buffered_message":"The video has been buffered as requested and is ready to play.","not_supported":"Not Supported","on":"On","off":"Off","click_to_enable_for_this_site":"Click to enable for this site","desktop_notification_denied":"You have denied permission for desktop notification for this site","notification_status_delimitor":";","error":"Error","adblock_interferance_message":"Adblock (or similar extension) is known to interfere with SmartVideo. Please add this url to adblock whitelist.","calculating":"Calculating","waiting":"Waiting","will_start_buffering_when_initialized":"Will start buffering when initialized","will_start_playing_when_initialized":"Will start playing when initialized","completed":"Completed","buffering_stalled":"Buffering is stalled. Will stop.","stopped":"Stopped","hr":"Hr","min":"Min","sec":"Sec","any_moment":"Any Moment","popup_donate_to":"Donate to","extension_id":null},"prefs":{"desktopNotification":true,"soundNotification":true,"logLevel":0,"enable":true,"loop":false,"hidePopup":false,"autoPlay":false,"autoBuffer":true,"autoPlayOnBuffer":false,"autoPlayOnBufferPercentage":42,"autoPlayOnSmartBuffer":true,"quality":"default","fshd":false,"onlyNotification":false,"enableFullScreen":true,"saveBandwidth":false,"hideAnnotations":false,"turnOffPagedBuffering":false}}" event="preferencesUpdated" id="myTubeRelayElementToPage"></mytubeelement><mytubeelement data="{"loadBundle":true}" event="relayPrefs" id="myTubeRelayElementToTab"></mytubeelement>

Insufficient memory to continue the execution of the program while opening wpf window using showdialog

$
0
0

Hi,

I am using windows7 embedded system, i am getting insufficient memory issue intermittent.

LogEntry><Level>ERROR</Level><DateTime>14/10/2014 09:44:59</DateTime><Logger>Lotus.TILL.Common.Services.LoggingService</Logger><Message>Insufficient memory to continue the execution of the program.</Message><Details>System.OutOfMemoryException: Insufficient memory to continue the execution of the program.
   at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
   at System.Windows.Media.MediaContext.CompleteRender()
   at System.Windows.Interop.HwndTarget.OnResize()
   at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags)
   at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.CreateSourceWindowDuringShow()
   at System.Windows.Window.SafeCreateWindowDuringShow()
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Window.Show()
   at System.Windows.Window.ShowDialog()
   at Lotus.TILL.Infrastructure.UI.Controls.DialogWindow.OpenDialogWindow(Window owner, BaseViewModel content, DialogAnimationType animationType, Object contentData) in d:\TFS Rajnikant\Release\Lotus 0_0_7_15\TILL\Application\LotusTILLInfrastructure\Lotus.TILL.UI\Controls\DialogWindow.xaml.cs:line 65
   at Lotus.TILL.UI.ShellViewModel.LoadCustomDialog(Double dialogHeight, Double dialogWidth) in d:\TFS Rajnikant\Release\Lotus 0_0_7_15\TILL\Application\LotusTILLUI\Lotus.TILL.UI\ShellViewModel.cs:line 4615
   at Lotus.TILL.UI.ShellViewModel.DiscoverDialog(ToolbarItem selectedToolBarItem, Boolean needToStartPayPointCommitProcess) in d:\TFS Rajnikant\Release\Lotus 0_0_7_15\TILL\Application\LotusTILLUI\Lotus.TILL.UI\ShellViewModel.cs:line 4390</Details><StackTrace>  at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
   at System.Windows.Media.MediaContext.CompleteRender()
   at System.Windows.Interop.HwndTarget.OnResize()
   at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags)
   at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.CreateSourceWindowDuringShow()
   at System.Windows.Window.SafeCreateWindowDuringShow()
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Window.Show()
   at System.Windows.Window.ShowDialog()
   at Lotus.TILL.Infrastructure.UI.Controls.DialogWindow.OpenDialogWindow(Window owner, BaseViewModel content, DialogAnimationType animationType, Object contentData) in d:\TFS Rajnikant\Release\Lotus 0_0_7_15\TILL\Application\LotusTILLInfrastructure\Lotus.TILL.UI\Controls\DialogWindow.xaml.cs:line 65
   at Lotus.TILL.UI.ShellViewModel.LoadCustomDialog(Double dialogHeight, Double dialogWidth) in d:\TFS Rajnikant\Release\Lotus 0_0_7_15\TILL\Application\LotusTILLUI\Lotus.TILL.UI\ShellViewModel.cs:line 4615
   at Lotus.TILL.UI.ShellViewModel.DiscoverDialog(ToolbarItem selectedToolBarItem, Boolean needToStartPayPointCommitProcess) in d:\TFS Rajnikant\Release\Lotus 0_0_7_15\TILL\Application\LotusTILLUI\Lotus.TILL.UI\ShellViewModel.cs:line 4390</StackTrace></LogEntry>

I am no doing any fancy stuff over here.

This is my LoadCustomDialog method

public void OpenDialogWindow(Window owner, BaseViewModel content, DialogAnimationType animationType, object contentData = null)
        {
            //Set content and owner of the dialog window
            Owner = owner;

            if (owner != null && owner is DialogWindow)
                ((DialogWindow)owner).CustomDialogMask.Visibility = System.Windows.Visibility.Visible;

            if (contentData != null)
                Root.Content = contentData;
            else
                Root.Content = content;

            this.DataContext = content;

            //checks whether the current thread is already running window as dialog or not
            //if (System.Windows.Interop.ComponentDispatcher.IsThreadModal)
            //    return;

            StartLoadingDialogAnimation(animationType);
            ShowDialog();
        }

Animations are not enabled.

Thanks,

Rajnikant

Visual Studio 2012 Express with C#: SQL Server 2012 Management Studio Database-Data Source & Connection String stop working?

$
0
0

Hi all,

I have a database "Books-Authors" (with 2 tables) in my Microsoft SQL Server 2012 Management Studio.  In the WPF application of Microsoft Visual Studio 2012 Express, I launched a project of databiding and connection string (named"scWpfApp1_BookAuthors") for displaying the desired/extracted data of the database "Books-Authors" on the FillDataGrid of my WPF application "scWpfApp1_BookAuthors".         MainWindow.xaml.cs is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;


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

        private void FillDataGrid()
        {
            String ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            String CmdString = String.Empty;
            using (SqlConnection con = new SqlConnection(ConString))
            {
              CmdString = "Select BookID, BookTitle, AuthorID from dbo.Table_1_Books";
              SqlCommand cmd = new SqlCommand(CmdString, con);
              SqlDataAdapter sda = new SqlDataAdapter(cmd);
              DataTable dt = new DataTable("Books");
              sda.Fill(dt);
              DataGrid_Loaded.ItemsSource = dt.DefaultView;
            }
        }
     }
}
   

I did BUILD on this project OK. But, I did START Without DEBUGGING and I got the message: scWpfApp1_BookAuthors has stopped working. I did Debugging and I got the following messages:

I don't know why the "ConString" does not work.  Please kindly help, tell me where I made the mistales in Connection Strings and/or Data Binding, and how to resolve the problem.                                           Thanks in advance,  Scott Chang

P. S. App.config is:

<?xml version="1.0" encoding="utf-8" ?><configuration><configSections></configSections><connectionStrings><add name="ConString"
            connectionString="Data Source=NAB-WK-02657306\SQLEXPRESS;Initial Catalog=BooksAuthorsLibrary;Integrated Security=True"
            providerName="System.Data.SqlClient" /></connectionStrings><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup></configuration>




How to set a RadioButton's IsChecked property from the style of its image content?

$
0
0

Hi everyone.

I have this code:

<UserControls:RadioButtonExtension Name="MyRadio"
                                                           Style="{StaticResource SoemStyle}"
                                                                      GroupName="SomeGroup"><Image Name="SomeImage"><Image.Style><Style TargetType="{x:Type Image}"><Setter Property="Stretch"
                                                Value="Fill" /><Setter Property="Source"
                                                Value="{Binding Path=Icon, Converter={StaticResource pathToImageConverter}}" /><Style.Triggers><DataTrigger Binding="{Binding Path=IsChecked, ElementName=SomeImage}"
                                                         Value="True"><Setter Property="Source"
                                                        Value="{Binding Path=Icon,
                                                        Converter={StaticResource SomeConverter}}" /></DataTrigger><DataTrigger Binding="{Binding Path=IsChecked, ElementName=SomeImage}"
                                                         Value="False"><Setter Property="Source"
                                                        Value="{Binding Path=Icon, Converter={StaticResource SomeVConverter}}" /></DataTrigger></Style.Triggers></Style></Image.Style></Image></UserControls:RadioButtonExtension>

What it does it, when Radio button is checked it loads one image and when unchecked it loads another image for the same button.

What I want now is, from the image control inside I want to set the IsChecked property of the Radio Button.

Something like:

  <Image Name="buttonImage">
                                <Image.Style>
                                    <Style TargetType="{x:Type Image}">
                                        <Setter Property="Stretch"
                                                Value="Fill" />
                                        <Setter Property="Source"
                                                Value="{Binding Path=Icon, Converter={StaticResource SomeConverter}}" />
                                       <Setter Property="{Binding Path=IsChecked, ElementName=PART_DataViewImageOne}"
                                                Value="False"/>

Of course it doenst work as I cant set Property to a binding!

Is there any way to do this?

Thank you.


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

Why we use Setter with Style instead of Setters ?

$
0
0

Hi,

I was wondering about the use of <Setter> and <Style.Setters> . I wondered why I can't use <Style.Setter> .  Because Setter is not a property of Style class. Thats good, but then why we are allowed to nest Setter inside Style, if its not a member of Style ? 


Resizing Textbox Control in Grid

$
0
0

Hi

I have a Grid control for user input data form entry with TextBox control as below.  As you see the TextBox is not stretching when I am maximizing the windows.  I want the textbox to remain anchored Left but stretch as window changes size.  I used this xaml at the moment thinking Width="Auto" would do the job but isnt working. 

<TextBox Height="23" Width="Auto" MinWidth="100" VerticalAlignment="Center" HorizontalAlignment="Left"

Name="firstNameTBox" Grid.Column="1" >


Using Converters in WPF

$
0
0

Hello,

I am confused whether to use converter or not in the below scenario:

<Label Content="{StaticResource strAge}" Visibility="{Binding IsAgeVisible}"  Grid.Row="4" Grid.Column="3" Margin="5,4,-4,4" HorizontalAlignment="Left" VerticalAlignment="Center" Style="{StaticResource FieldLabelStyle}"/>

The above is a label and I am binding its Visibility property to a Property IsAgeVisible as declared below:

        public Visibility IsAgeVisible
        {
            get
            {
                return _isAgeVisible;
            }
            set
            {
                _isAgeVisible = value;
                 RaisePropertyChanged(() => IsAgeVisible);
            }
        }

Now I am not sure whether this is a good approach or i should use a bool property and then a boolToVisibility Converter in my xaml.

Just for information that this property will be called on two times : 1) On Load 2)Whenever value in the control from which it gets raised changes (it is a datepicker).

Suggestions Appreciated.

Thanks,

Abdi


C# WPF datagridtextcolumn change color

$
0
0

Hi all,

I want to change color of a dataGrid cell when it value is greatThen or lessThen ... I tried many examples from web but nothing goes right ... so something I wanna sth like this ...

<DataGrid>

<DataGrid.Columns><DataGridTextColumn Header="Number" Width="170" Binding="{Binding Path=bindNumber}"><DataGridTextColumn.ElementStyle><Style TargetType="{x:Type TextBlock}"><Style.Triggers><Trigger Property="Text" Value="<0"> //less then<Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style></DataGridTextColumn.ElementStyle></DataGridTextColumn>

</DataGrid.Columns>

</DataGrid>

Thank you for answers


I want to remove xmlns="" in XML

$
0
0

hi

I just want to replace the code 1 with the code 2 in xml file below.

but, when I use XElement.Parse("<Plugin Id="Layout2" Assambly="LayoutAssambly2"/>") and then use XElement.RepalceWith method

to replace code 1 in xml file , xmlns="" was writed as the attribute like the code 2

Could anyone tell me how to remove the xmlns=""  ?

Thank you very much

Code 1 :<Plugin Id="Layout" Assambly="LayoutAssambly"/>

Code 2 : <Plugin Id="Layout2" Assambly="LayoutAssambly2" xmlns=""/>

Xml file

<?xml version="1.0" encoding="utf-8"?><Extension xmlns="http://www.google.com"><Group><Plugin Id="Layout" Assambly="LayoutAssambly"/></Group></Extension>



StrokeThickness accounted for in Shape size only on the right and bottom

$
0
0

Hello all,

I am finally after all these years of writing native and WinForms/.NET programs trying to learn the WPF and WinRT APIs. It's great feeling like a novice again, but it's also a little frustrating. I am hoping someone can help alleviate some of my confusion. :)

I have already amassed a large number of questions, but for now I will just pose questions about one particular issue:when I try to define a Path element, its size apparently takes into account only the right and bottom of the shape, and the origin is not adjusted to accommodate the StrokeThickness value.

(I suppose one way to look at it also is that if the origin of the object were to take into account the StrokeThickness, then for the given ActualWidth and ActualHeight values, it would be the left and top that took the stroke thickness into account...but either way, the total width and height of the object is less than the actual rendered size by half the stroke thickness).

I have copied the XAML for the page below. Ultimately, I am trying to define some shapes programmatically, but the immediate problem is easily reproduced using just a static XAML description. Most of the XAML is there just to help illustrate the issue. The Path element is of course the problematic element. The TextBlocks are there to show me what the various size member values are, and the unfilled Rectangle elements are there to give me a graphical indication of some of those values (with the text background set to the same color as the corresponding rectangle).

I have implemented something similar using the Visual object, but in that case the computed bounds (a Rectangle value) of the Visual is correct and in fact also reflects the origin of the object, the starting point of the underlying Geometry object. But unfortunately, the WinRT API does not support the Visual class and since I'd like to keep the code as similar for WPF and Winrt as I can, I'm stuck using the Path shape object, which doesn't seem to have a full Rectangle "bounds" property like the Visual class does, nor do the width and height values for the shape seem to be correct.

For extra credit: I also have noticed that while the light yellow rectangle that is supposed to show the RenderedSize value on the drawing seems to work find in the Visual Studio Designer for the page, it doesn't show up at all when I actually run the program. Please see the screenshots at the bottom of this post.

Please tell me what I need to do in order to successfully determine the actual and complete size of my rendered Path element, including the stroke thickness. And if possible, please also explain how to get the RenderedSize rectangle to display correctly.

Here's the XAML for my page:

<Window x:Class="TestWpfDesiredRenderedSizeBug.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"><StackPanel Margin="0,5,0.4,-5.2"><StackPanel Orientation="Horizontal"><TextBlock Text="DesiredSize: " FontSize="20"/><TextBlock Text="{Binding DesiredSize, ElementName=path, Mode=OneWay}" FontSize="20"/><TextBlock Text="RenderSize: " FontSize="20" Margin="20, 0, 0, 0" Background="LightGoldenrodYellow"/><TextBlock Text="{Binding RenderSize, ElementName=path, Mode=OneWay}" FontSize="20"/></StackPanel><StackPanel Orientation="Horizontal"><TextBlock Text="ActualWidth: " FontSize="20" Background="Red"/><TextBlock Text="{Binding ActualWidth, ElementName=path, Mode=OneWay}" FontSize="20"/><TextBlock Text="ActualHeight: " FontSize="20" Padding="20, 0, 0, 0"/><TextBlock Text="{Binding ActualHeight, ElementName=path, Mode=OneWay}" FontSize="20"/></StackPanel><StackPanel Orientation="Horizontal"><TextBlock Text="Data.Bounds: " FontSize="20" Background="SpringGreen"/><TextBlock Text="{Binding Data.Bounds, ElementName=path, Mode=OneWay}" FontSize="20"/></StackPanel><Grid HorizontalAlignment="Left" VerticalAlignment="Top"><Grid.LayoutTransform><ScaleTransform ScaleX="1" ScaleY="1"/></Grid.LayoutTransform><Path x:Name="path" Fill="Yellow" Stroke="Black"
                  StrokeThickness="10" Data="M0,0 L50,0 L50,50 L0,50 L0,0"
                  StrokeStartLineCap="Round" StrokeLineJoin="Round" StrokeEndLineCap="Round"
                  HorizontalAlignment="Left" VerticalAlignment="Top" /><Rectangle Fill="Transparent" Stroke="Red" StrokeThickness="1"
                       Width="{Binding ActualWidth, ElementName=path, Mode=OneWay}"
                       Height="{Binding ActualHeight, ElementName=path, Mode=OneWay}"
                       HorizontalAlignment="Left" VerticalAlignment="Top" /><Rectangle Fill="Transparent" Stroke="LightGoldenrodYellow" StrokeThickness="1"
                       StrokeDashArray="3 5"
                       StrokeDashOffset="4"
                       Width="{Binding RenderSize.Width, ElementName=path, Mode=OneWay}"
                       Height="{Binding RenderSize.Height, ElementName=path, Mode=OneWay}"
                       HorizontalAlignment="Left" VerticalAlignment="Top" /><Rectangle Fill="Transparent" Stroke="SpringGreen" StrokeThickness="1"
                       StrokeDashArray="3 5"
                       Width="{Binding Data.Bounds.Width, ElementName=path, Mode=OneWay}"
                       Height="{Binding Data.Bounds.Height, ElementName=path, Mode=OneWay}"
                       HorizontalAlignment="Left" VerticalAlignment="Top" /></Grid></StackPanel></Window>

And here are the screenshots, from the VS Designer and the window at run-time, respectively (note that in both, the stroke of the Path shape "bleeds" outside the boundary of the shape on the left and top):

Visual Studio Designer representation of the page, showing all three rectangle outlines

Window at runtime, showing only the ActualWidth and Data.Bounds rectangles. The RenderSize rectangle is missing (or empty)

what happens behind the seen on closing window in C# wpf

$
0
0

I am passing object of Window1 as reference to Window2 using this. Then I close Window1 and try to show Window1 using button click from Window2.
I am getting an error which is often possible with with any developer in wpf. Error is:Cannot set visibility or call Show, ShowDialog after a window has closed.

button click method in Window1.xaml.cs

{
  Window2 w2 = new Window2();
  w2.w1Obj = this;
  w2.show();
}

Then I close Window1.

button click method in Window2.xaml.cs

{
  w1Obj.testMethod();
  this.w1Obj.show();
}
Here `testMethod()` is executed well but when I want to show that window, it gets crashed. so I want to know what happens in memory or whatever to Window1 object when I closed that Window.? Is this memory leak.?



How to use TypeConverter with EntityFramework edmx file?

$
0
0

Dear Gurus!

I use Entity Framework, and in entity class i am use attribute

[Xceed.Wpf.Toolkit.PropertyGrid.Attributes.ItemsSource(typeof(punctsList))]

public Nullable<global::System.Int32> code
        {
            get
            {
                return _code;
            }
            set
            {
              ...
            }
        }

For editing that entity I use propertyGrid , and user can change this property with help of drop-down list. But I need only 

to convert int value of property to string value by converting it with use of  database table. I have try to use type converter :

       class PunctConverter : TypeConverter
       {

           public PunctConverter()
           {

           }

           public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
           {
              return true;
           }
           public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
           {
               return someStringFromDatabase;
           }

       }

And use next attribute:

        [TypeConverter(typeof(PunctConverter))]

        public Nullable<global::System.Int32> code
        {
            get
            {
                return _code;
            }
            set
            {
...
            }
        }
But conversion is not performed. Is it right way?

Viewing all 18858 articles
Browse latest View live