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

DataGridCellStyle: Set Background of DataGridCell based on value in a Different DataGrid / DataTable

$
0
0

Hi everyone

I am trying to set the background of a cell in a datagrid based on a value in a different datagrid. Is it possible to specify this in the XAML through binding? I'm using the MVVM pattern and would like to minimise code in the code behind. Please note that the datagrids are the same dimension, but the dimension is unknown until runtime.

I've copied an image of the two datagrids. Essentially, the second datagrid will contain values of 0 or 1. I would then like to color the cells in the first datagrid a different color based on these values. 

CODE:

<DataGrid Style="{StaticResource Style1}" ItemsSource="{Binding Table1, StringFormat=n}" AutoGenerateColumns="True" ><DataGrid.InputBindings><MouseBinding MouseAction="LeftDoubleClick" Command="{Binding CommandWithParameter}" CommandParameter="{Binding .}"/></DataGrid.InputBindings><DataGrid.CellStyle><Style TargetType="DataGridCell"><Setter Property="Background" Value="{Binding Table2, Converter={StaticResource WeightConverter} }"/></Style></DataGrid.CellStyle></DataGrid>

Thanks!


DataGridCellStyle: Set Background of DataGridCell based on value in a Different DataGrid / DataTable

WPF: Why empty DatePicker does not detect in binding property?

$
0
0

Our application use WPF DatePicker.

There are several cases the system need to validate DateValue in DatePink before enable OK button in the page.

1) DateValue is required if the datevalue is empty.

2) DateValue must be great than today

3) DateValue is in invalid format.

<DatePicker x:Name="datePickExpireDate"
          HorizontalAlignment="Left"
          VerticalContentAlignment="Center"
          VerticalAlignment="Center"
          SelectedDate="{Binding ExpireDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          Loaded="datePickExpireDate_Loaded"
          CalendarStyle="{StaticResource styleCalendar}" ><DatePicker.Resources><Style TargetType="{x:Type DatePickerTextBox}"><Setter Property="BorderBrush" Value="Transparent"></Setter><Setter Property="BorderThickness" Value="0"></Setter><Setter Property="Control.Template"><Setter.Value><ControlTemplate><!--<TextBox x:Name="PART_TextBox" VerticalContentAlignment="Center" VerticalAlignment="Stretch" Margin="-1,-1, 0, -2"
                         Text="{Binding Path=SelectedDate, StringFormat={}{0:MM/dd/yyyy}, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />--><TextBox x:Name="PART_TextBox" VerticalContentAlignment="Center" VerticalAlignment="Stretch" Margin="-1,-1, 0, -2"
                         Text="{Binding Path=ExpireDate, StringFormat={}{0:MM/dd/yyyy}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /></ControlTemplate></Setter.Value></Setter></Style></DatePicker.Resources></DatePicker>

We notice that if we style invalid DateValue such as "asdf" and DatePicker lost focus, it will make the TextBox Border becomes right. However, it does not trigger the ExpireDate change in ViewModel class.

When the text in DatePicker TextBox changes, we need it to trigger ExpireDate change so we can base ExpireDate value to validate and show proper error message.

How do we fix this case? Thx!


JaneC

Cannot register duplicate name '' in this scope?

$
0
0

This question is related to this question. I used to set the dataContext in the constructor of the userControl, but then I was not able to hide the UseControl, therefore I gave a name to the UserControl and used bind to the element name. 

Now when I try to save the canvas I am getting the following errors:

It's obviously because I used the same userControl in the Canvas more than once! The question is how can I Save the Canvas and at the same time achieve a resolution for the previous question?

                using (MemoryStream ms = new MemoryStream())
                {

                        Canvas canvasTemp = new Canvas();
                        XamlWriter.Save(canvas, ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        canvasTemp = XamlReader.Load(ms) as Canvas;
                        Section section = new Section();
                        Paragraph para = new Paragraph();

                        para.Inlines.Add(canvasTemp);
                        section.Blocks.Add(para);
                        section.BreakPageBefore = true;
                        fd = new FlowDocument();
                        //fd.PageWidth = PrintLayout.A4.ColumnWidth;
                        fd.Blocks.Add(section);

                }

Button

$
0
0
<Button x:Name="btnKesmeStartTime" Style="{DynamicResource ConnectButton}" />
How do  I write with code,the above part 

TextBox's text input in WPF

$
0
0

The input in my textBox is strange.

if for ex. i insert 5, it shows me: 5D5

And if I write 4 from NumPads, it shows me 4NumPad4

i didn't define anything to do it. what do i need to check, and what do i need to change?


Slider.IsMoveToPointEnabled aborts mouse click events

$
0
0
When IsMoveToPointEnabled is set the Thumb of a Slider moves immediately to the location of the mouse click.
Unfortunately setting this property to true will cause that no mouse clicks will be forwarded anymore when you click on the Track (RoutedEventArgs.Handled is set to true). I understand that the control catches a mouse down event internally but why is RoutedEventArgs.Handled always set to true? Now a mouse down event is only raised when I click on the thumb but that is not the behavior I need.
So what can I do?
Here a simple sample code:

Code Snippet

<Windowx:Class="RoutedEvents.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="clr-namespace:RoutedEvents"

    Title="RoutedEvents"Height="300"Width="400">

  <StackPanel>

    <CheckBoxx:Name="_checkBox"Content="IsMoveToPointEnabled"/>

    <TextBlockText="Check/Uncheck CheckBox and click on Track of the Slider control."/>

    <Sliderx:Name="_slider"IsMoveToPointEnabled="{Binding ElementName=_checkBox, Path=IsChecked}"/>

  </StackPanel>

</Window>


Code Snippet

public Window1()

{

    InitializeComponent();

 

    _slider.PreviewMouseDown += Show;

    _slider.PreviewMouseLeftButtonDown += Show;

    _slider.MouseDown += Show;

    _slider.MouseLeftButtonDown += Show;

}

 

void Show(object sender, MouseButtonEventArgs e)

{

    MessageBox.Show(e.RoutedEvent.Name);

}



Thanks,
Alex

[WPF] Use element of another UserControl

$
0
0

Hi,

I have included an UserControl "B" into another UserControl "A".... so, I would refresh/update the datagrid "dgPlan" defined in UserControl "A" from UserControl "B".

The application give me an error, because "dgPlna" is not defined, how can I defined it in UserControl "B"?

Thanks.


convert to c#

$
0
0

Hi All.

How to convert from VB to C#

ABCTableAdapter.Fill(CtrlDataSet1.DuplP, Emp_Id, TextBox1.Text, Duplicate)

and

Me.TextBox1.ToolTip = "The Emp # - " & EmpDuplSource.View.CurrentItem("Emp_No") & " duplicated."

Thanks.

Which event does Perforator use to calculate FPS?

$
0
0

I'm need to add code to measure FPS, same way perforator does. The closest I got to official documentation was http://blogs.msdn.com/b/jgoldb/archive/2008/09/26/etw-event-tracing-in-wpf.aspx , and there they use UceNotifyPresent. I don't get this event or WClientUceNotifyPresent. The only events I get that are at the same rate as what Perforator shows are:

WClientUceRender/Stop, WClientUcePresent/Start, WClientUcePresent/Stop, WClientUceResponse

I'm betting on the last one, but it would be nice to get confirmation.

Making an Array of Textblocks and displying on the screen when the app is running

$
0
0

Hello everyone

I am new to this UI development. I am making a reverse game model and I want show my

character array contents on text-blocks. I want to make an array of these text-blocks  and show them on screen

if there is another simple method please suggest me.

What WPF method gives the same KeyChar like in C#?

$
0
0

in C#  there's a method KeyChar. when inserting a key in to a textBox it gives the value that was insert. for ex. when clicking on:5 the method gives: 5.

but Wpf doesn't have the KeyChar method.

i tried to use Key but then it gives me for ex. when i click: 5, i get: 5D5.

what method can i use to get the KeyChar like in C#?

or, maybe there's no such method and then i'll have to build one as an extension?

printDocument in WPF

$
0
0

I' m transleting a project from C# to WPF.

In C#, I have the toolbox "printing" printDocument1 to print a game.

Here his definition in Game.designer :

 this.printPreviewDialog1.Document = this.printDocument1;

 And the function event  printDocument1_printpage in the cs code :

 private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            Bitmap bmp = new Bitmap(this.Width, this.Height);
            this.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));


            e.Graphics.DrawImage(bmp,
                new RectangleF(150, 200, 500, 700),
                new RectangleF(board2.Left, board2.Top, board2.Width, board2.Height),
                GraphicsUnit.Pixel);


        }

How can I do it in WPF ?

I tried a few things but it still not work. I have a btnPrint with a printDialog and a printPreviewDocument. It prints a blank page and it shows a blank document in the printPreview "the document does not contains any page". Here my btnPrint_MouseDow function in WPF :

 private void btnPrint_MouseDown(object sender, MouseButtonEventArgs e)
        {

            System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
            System.Windows.Forms.PrintPreviewDialog printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();


            if (printDialog.ShowDialog() == true)
                printPreviewDialog1.ShowDialog();

            if (printDialog.ShowDialog() == true)
                printDialog.PrintVisual(board2, "my game");

        }
Do you have an idea ?

Can't view my user control in the designer (An Unhandled Exception has occurred)

$
0
0

I'm using VS 2012, looking at some code I wrote some time ago. For some reason I cannot view the XAML in the design view, only the XAML view. I'm getting an error that says, "An Unhandled Exception has occurred". I can compile the solution fine, but it won't let me view it. I don't know why I can't view it in the designer. Here's the error details:

Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteException
Object reference not set to an instance of an object.
   at System.Windows.StyleHelper.FindNameInTemplateContent(DependencyObject container, String childName, FrameworkTemplate frameworkTemplate)
   at System.Windows.TemplateNameScope.System.Windows.Markup.INameScope.FindName(String name)
   at MS.Internal.Data.ElementObjectRef.GetObject(DependencyObject d, ObjectRefArgs args)
   at MS.Internal.Data.ObjectRef.GetDataObject(DependencyObject d, ObjectRefArgs args)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.VerifySourceReference(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
   at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.UIElement.UpdateLayout()
   at System.Windows.Interop.HwndSource.SetLayoutSize()
   at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
   at System.Windows.Interop.HwndSource.set_RootVisual(Visual value)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteUIElement.<>c__DisplayClass12.<Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteUIElement.CreateContent>b__11()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass16`1.<MarshalIn>b__15()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.Invoke(Boolean waitingInExternalCall)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.InvokeCall(Call call)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.ProcessQueue(CallQueue queue)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.ProcessInboundAsyncQueue(Int32 identity)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.ProcessMessage(Int32 msg, IntPtr wParam, Boolean elevatedQuery, Boolean& handled)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.OnWindowMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.MessageOnlyHwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at Microsoft.Expression.DesignHost.Isolation.IsolationProcess.RunApplication()
   at Microsoft.Expression.DesignHost.Isolation.IsolationProcess.<>c__DisplayClass2.<Main>b__0()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()


Rod

Player piano transform for a text block?

$
0
0

I've been able to *almost* find what I was looking for but not exactly.

I've got several textblocks that will be updating periodically based on a SQL query. The data will typically be larger than the text block can hold so I'm thinking putting it into a wrap panel.  I need it to scroll upwards at selectable rate of speed as if it's on a roll of paper and stay confined to the area.  I found an example online of using a storyboard using DoubleAnimation, but I need it to be able to disappear as it reaches the top of the block, and not go outside it and not just jump to the bottom of the screen. It needs to be more like as if it's on a continuous sheet.

Basically it will be a news and events display that will have information about events, the weekly cafeteria menu, upcoming birthdays.

Here is what I have now.  I have not got the WrapPanel going yet.  I've got to read up on it.

And If I'm using the wrong controls for what I'm doing, please suggest something more appropriate.

<TextBlock Background="Transparent" HorizontalAlignment="Left" FontSize="48" Foreground="White" Height="265" Width="900" Margin="15,550,0,0" VerticalAlignment="Top" Text="Carter Blood Drive will be Wednesday asdfljksadflkjsadfkljhsadfkljhsadflk sadfj hsadkl hsadjklf hsadfkljhsadfkljhsad flkjsad hksadlj h jklhsd fjklhsadfkl jhsadkl fjhsadl fjkhsadljkh sad jk hsad klj hsadfkljhsad fklj hkljsad fhljksad hksadlj h fsa"><TextBlock.RenderTransform><TranslateTransform x:Name="translate" /></TextBlock.RenderTransform><TextBlock.Triggers><EventTrigger RoutedEvent="FrameworkElement.Loaded"><BeginStoryboard><Storyboard RepeatBehavior="Forever"><DoubleAnimation
                                From="260" To="0"
                                Storyboard.TargetName="translate"
                                Storyboard.TargetProperty="Y"
                                Duration="0:0:5" /></Storyboard></BeginStoryboard></EventTrigger></TextBlock.Triggers></TextBlock>



How to call sys.sp_setapprole stored procedure using WPF MVVM using EF6

$
0
0
Is scope of the edmx context connection will be through out an application or within the method?

Bind tiles to objects:

$
0
0

Hi,

I'm very new WPF.

I've some set of tiles. (created using border) I want to bind each of the tile to different objects. Can anybody please let me know how I can achieve this?

Thanks,

Santosh

C# How to Get Windows Version

$
0
0

Hi guys,

Im on a Project in WPF!

Well however I wanna check the Windows OS by MessageBox.Show(Environment.OSVersion.ToString());

I tried that on Windows 8.1 and I got as result: 6.3.9600.0

Well, on the Windows Server 2012 R2 i get the same result. I informed a little bit and found out with wikipedia:

Wikipedia Link

that Windows 8.1 and the Windows Server 2012 R2 have the same OS Version.

the same is with Windows 8 and Windows Server 2012

Is there any way to defferentiate Windows 8.1 and the Windows Server 2012 R2 resp. Windows 8 and Windows Server 2012

It would be important.

Thanks Guys!

DataGrid cells with controls in them

$
0
0
I have a data grid where i need a different editor/displayer in a cell dependent on the type of the cell.  How do I set the editor/displayer for a cell?

Saving canvas as xps the style doesn't work?

$
0
0
<Rectangle Width="{Binding b}" Height="{Binding tt}" Stroke="Black" StrokeThickness="1" Canvas.Left="{Binding leftb}" x:Name="topPlateRect" Style="{StaticResource topPlateStyle}"><Canvas.Top><MultiBinding Converter="{l:PositionConverterNegative}"><Binding Path="(Canvas.Top)" ElementName="gussetLeftRect"/><Binding Path="Height" RelativeSource="{RelativeSource Self}"/></MultiBinding></Canvas.Top></Rectangle>


<Style x:Key="topPlateStyle" TargetType="{x:Type FrameworkElement}"><Setter Property="Visibility" Value="Collapsed"/><Style.Triggers><DataTrigger Binding="{Binding IsChecked, ElementName=topPlateCB}" Value="true"><Setter Property="Visibility" Value="Visible"/></DataTrigger></Style.Triggers></Style>

When I try to save the above rectangle which is in a canvas as an xps, the rectangle disappears for some reason. However, when I save it as .png the rectangle appears. 

public void SaveCanvasAsXps(Canvas canvas, string fileName) { SaveAsXPSMultipleFixedDocSeq(fileName, PaginatorToFixedDocSequence(DrawingToPaginator(canvas,pl.Size))); } private FixedDocumentSequence PaginatorToFixedDocSequence(DocumentPaginator paginator) { MemoryStream strm = new MemoryStream(); Package pkg = Package.Open(strm, FileMode.OpenOrCreate); string pack = "pack://" + Guid.NewGuid().ToString() + ".xps"; PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument xpsDoc = new XpsDocument(pkg, CompressionOption.Maximum, pack); XpsSerializationManager xpsSM = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false); xpsSM.SaveAsXaml(paginator); return xpsDoc.GetFixedDocumentSequence(); } public void SaveAsXPSMultipleFixedDocSeq(string fileName,FixedDocumentSequence fixedDocSeq) { //this.token = ct; //this.uiTask = uiTask; if (File.Exists(fileName)) try { File.Delete(fileName); } catch (Exception e) { MessageBox.Show(e.ToString()); return; } XpsDocument xps = new XpsDocument(fileName, FileAccess.ReadWrite, CompressionOption.Normal); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xps); writer.Write(fixedDocSeq); xps.Close(); }

   private DocumentPaginator DrawingToPaginator(Canvas canvas,Size pageSize)
        {

            DocumentPaginator paginator = null;

                using (MemoryStream ms = new MemoryStream())
                {

                        Canvas canvasTemp = new Canvas();
                        XamlWriter.Save(canvas, ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        canvasTemp = XamlReader.Load(ms) as Canvas;
                        Section section = new Section();
                        Paragraph para = new Paragraph();

                        para.Inlines.Add(canvasTemp);
                        section.Blocks.Add(para);
                        section.BreakPageBefore = true;
                        fd = new FlowDocument();
                        //fd.PageWidth = PrintLayout.A4.ColumnWidth;
                        fd.Blocks.Add(section);

                }

                if (fd.Blocks.Count > 0)
                {
                    //fd.Blocks.Add(para);
                    paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator;
                    //paginator = new DocumentPaginatorWrapper(paginator, pl.Size);
                    paginator = new DocumentPaginatorWrapper(paginator, pageSize);
                    paginator.PageSize = pl.Size;
                    //documentPaginators.Add(key, paginatorWrapper);
                    //bool ss = paginatorWrapper.IsPageCountValid;

                }
                //return paginatorWrapper;
                return paginator;
            //}
        }


Is there anyway that I could use style and at the same time save the canvas as xps? Thanks. 


Viewing all 18858 articles
Browse latest View live


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