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

TextBox character/letter spacing?

$
0
0

Back in WPF 3.5-4.0, I remember not being able to change the letter spacing for TextBox (and other Text elements) (not stretch nor scale, but spacing).

Is this achievable now with WPF (2018)?

For Labels/TextBlocks, I was able to use an ItemsControl. But not for TextBox.

If not, is there a page where I can request/vote for this (like Connect)?

And how can I workaround this in the meantime?

Thanks

mc

(2008) Increase the Character spacing in a textblock

(2010) Character spacing in a label



wpf

$
0
0

i have a canvas named MainCanvas and iam dragging a label called chemicalname to the canvas i want to resize this labe in runtime so plzzz help me

chromium browser in wpf, How to set string to textbox?

$
0
0

Hi,

I am loading the .php page as a tabcontrol item using wpf Chromium browser, My .php page contains Textbox (id=mytext)

I want to set the value for the test box from C# code, 

How can I do this, 

I am very new to chromium browser in wpf, and javascript,

Please help me to achieve this. Than in advance.


Accessing App.Config Appsettings sections from Class Libraries

$
0
0
Hi,

I Have a Solution Which has one WPF Desktop Application, 2 Class Libraries.
I have App.COnfig file in WPF Desktop Application and would like to access Appsettings sections and Connection Strings Sections from Class Libraries.

I am getting null when i try to access Appsettings section.

Please advice

Thanks,

ObservableCollection update cell via Column Number.

$
0
0

ObservableCollection<Model> update cell via Column Number.

     public ObservableCollection<Model> ViewModelCollection
        {
            get => _viewModelCollection;
            set
            {
                _viewModelCollection = value;
                OnPropertyChanged(nameof(ViewModelCollection));
            }
        }

  updateVm.Collection.ViewModelCollection[1].Dosage = rowData[rowDataIndex][columnDataIndex];


Update Code is Working....But My Requirement is instead Column Name ....I want to Update Via Column Number.

Something like this....

updateVm.Collection.ViewModelCollection[1][1]= rowData[rowDataIndex][columnDataIndex];

How do I Achieve this in ObservableCollection.


How to save WPF RichTextBox content (text + image) to the database

Change Cell Color in Datagrid

$
0
0

Hi Folks,

how can I change the background color in a WPF Datagrid after having it populated with data, depending on cell values?

I am able to change it on a single cell like this:

DataGridCell Cell = (DataGridCell)sender;

Cell.Background = Brushes.LightGreen;

But I wasn’t able to iterate through the entire datagrid to change the background of specific cells.

Any help is highly appreciated!

C@rsten


WPF and Custom Credential Provider in Windows 7

$
0
0

Hi there,

I'm asking a question similar to the one in thread "WPF loads slowly on logon and switch user when launched from custom Credential Provider" (I cannot include the link for some error in this page) because I'm having exactly the same problem one and a half year later. According to the response we should give up using WPF in a custom credential provider but this is a very costly option at this moment. Additionally the said thread is from March 2013 and the situation might have changed at this moment.

I found my custom credential provider is working great in Windows 8 and 8.1 and some platforms with Windows 7. But there are other platforms with Windows 7 where the WPF window takes 30 sec to show up. 

During my tests I created a very simple WPF application, with the Wizard and without any custom code. I run Visual Studio from the same logon UI session and from there I debug my simple WPF application. I detected the same problem (All in a specific Windows 7 and win32 platform, .NET 4.5.1).

From my debugging and performance anlysis, it seems the delay occurs in function

System.Windows.Application.Run (The ETL created with Performance Analyzer shows most exclusive time is consumed here).

According to the said thread, the problem occurs because the foreground WPF UI thread is blocked waiting for the WPF render thread (in background) which in turn is waiting for some driver to initialize hardware. 

It seems the UI thread finally timeout because the time is exactly 30 secs.

My question is if the response to the question mentioned above is still relevant today (October 2014) or there is already a solution to this issue.

It would be great if Keith Fink (the same guy that worked on the other issue) could follow up on this issue.

Thanks in advance,

Rodolfo



Performance Issue with Row Number but Column Number Working Super Fast.

$
0
0

Performance Issue with Row Number but Column Number Working Super Fast.

       foreach (DataGridCellInfo obj in datagrid.SelectedCells)
            {
               var selectedcells = new SelectedCellsModel
                {
                RowNumber = datagrid.Items.IndexOf(obj.Item),
                ColumnName = obj.Column.SortMemberPath
                };

                updateVm.Collection.SelectedCells.Add(selectedcells);
            }

Showing WPFHidden window using windowHandle

$
0
0
WPF window Code

var windowInteropHelper = new WindowInteropHelper(this);
int tempHandle = (int)windowInteropHelper.Handle;
string filePath = @"C:\windowHandleLog.txt";
if (File.Exists(filePath))
{
    File.Delete(filePath);
}
File.AppendAllText(filePath, tempHandle.ToString());
this.Hide();



Console Application Code:

[DllImport("User32")]

private static extern int ShowWindow(int hwnd, int nCmdShow);


string filePath = @"C:\windowHandleLog.txt";
string handle = File.ReadAllText(filePath);
int windowHandle = Convert.ToInt32(handle);
ShowWindow(windowHandle, SW_SHOW);

I have created one WPF window and added some control to it. Now I will get the window handle and hide the window.

I'll create the separate application (console) and use the windowHandleshow the window.

but the issue is the window is coming with the black background. Not showing the control.

Please refer above code.

Can anyone help how to get it done (Showing WPF window using window handle)

WPF Window:

Window Before

window After showing from using window handle

Window After showing from Console app or different application

Thanks & Regards,

Ashish Agrawal46 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="146" id="146">Thavote</g>




Referencing a StaticResource in another StaticResource

$
0
0

Hello,

I'm trying to set up my styles properly. Thus I've created an external ResourceDictionary for all common style attributes, in which I've defined a default font family like this:

<FontFamily x:Key="Default.FontFamily">Impact</FontFamily>

This way the family changes at all places when I change this single line.

using and referencing StaticResource

Now I want to use this default font family wherever nothing else is defined, which is in most places (but not all). However, I want to retain the ability of defining other font families for any place this is used. So I defined the default font explicitly for a group box header:

<StaticResource x:Key="GroupBox.HeaderFontFamily" ResourceKey="Default.FontFamily"/>

I use this on a TextBlock that is included in a template of my group box.

<Style x:Key="GroupBoxHeaderTextStyle" TargetType="{x:Type TextBlock}"><Setter Property="FontFamily" Value="{StaticResource GroupBox.HeaderFontFamily}"/></Style>

So far, this is working. However, as soon as I add another line:

<StaticResource x:Key="GroupBox.HeaderFontFamily" ResourceKey="Default.FontFamily"/><StaticResource x:Key="FormLabel.FontFamily" ResourceKey="Default.FontFamily"/>

I get this exception thrown:

Exception: Cannot find resource named 'Hsetu.GroupBox.HeaderFontFamily'. Resource names are case sensitive.

So I've experienced that WPF cannot find an Element directly addressed when followed by a StaticResource (Yes, this also counts for elements other than StaticResources. eg, if I tried to address the font family "Default.FontFamily" directly I would get the same error, because it precedes a StaticResource element)

using DynamicResource and referencing StaticResource

I've tried using a DynamicResource as I've read in an example to a similar problem:

<DynamicResource x:Key="GroupBox.HeaderFontFamily" ResourceKey="Default.FontFamily"/><DynamicResource x:Key="FormLabel.FontFamily" ResourceKey="Default.FontFamily"/>

This throws the following error:

ArgumentException: 'System.Windows.ResourceReferenceExpression' is not a valid value for property 'FontFamily'.

using and referencing DynamicResource

Using DynamicResource in my group box style only changed the error message:

<Style x:Key="GroupBoxHeaderTextStyle" TargetType="{x:Type TextBlock}"><Setter Property="FontFamily" Value="{DynamicResource GroupBox.HeaderFontFamily}"/></Style>

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.ResourceReferenceExpression' to type 'System.Windows.Media.FontFamily'.'

adding a dummy element

So, as this problem only occurs when my StaticResource is followed by another, I've got the idea of including a dummy element between the resources.

<StaticResource x:Key="GroupBox.HeaderFontFamily" ResourceKey="Default.FontFamily"/><Separator x:Key="Dummy"/><StaticResource x:Key="FormLabel.FontFamily" ResourceKey="Default.FontFamily"/>

Now, this works. Hooray! But wait a minute... continuing on, I tried to use the second resource "FormLabel.FontFamily"

<Style x:Key="FormLabelStyle" TargetType="{x:Type Label}"><Setter Property="FontFamily" Value="{StaticResource FormLabel.FontFamily}"/></Style>

This throws another exception now:

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.Separator' to type 'System.Windows.Media.FontFamily'.'

Bug?

I'm not even using the Separator at all, so what is going on? I assume, when addressing a StaticResource, WPF actually tries to use the preceding element - which only worked in the beginning because the preceding element was a FontFamily by chance - and not the element that is referenced with the ResourceKey. At the same time, rendering the preceding element inaccessible directly. In order to confirm my suspicion, I've replaced the Separator with another FontFamily.

<StaticResource x:Key="GroupBox.HeaderFontFamily" ResourceKey="Default.FontFamily"/><FontFamily x:Key="Dummy">Courier New</FontFamily><StaticResource x:Key="FormLabel.FontFamily" ResourceKey="Default.FontFamily"/>

And indeed, it worked, but the Labels are now using the Courier New font instead of the referenced Impact font.

Btw. this does not only happen with font families but also other attributes (FontSize, BorderThickness, FontWeight, etc.). So, is this actually a bug in WPF or are StaticResources supposed to act like this (which wouldn't make any sense to me)? How can I get to use my font family in multiple places only defining it once?

Need Example of Using CommonServiceLocator in MVVM Environment with Prism and Unity

$
0
0

The following code compiles but fails at this line: "var fluentRibbonRegionAdapter = ServiceLocator.Current.GetInstance<RibbonRegionAdapter>();".

The error message is ' ServiceLocationProvider must be set.'

using CommonServiceLocator;
using Prism.Modularity;
using Prism.Regions;
using Prism.Unity;
using MyApp.Infrastructure.RegionAdapters;
using MyApp.Prism;
using MyApp.Views;
using System.Windows;
using System.Windows.Controls;

namespace MyApp.Startup
{
    public class Bootstrapper : UnityBootstrapper
    {

        protected override IModuleCatalog CreateModuleCatalog()
        {
            var catalog = new DirectoryModuleCatalog { ModulePath = @".\Modules" };
            return catalog;
        }

        protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
        {
            var mappings = base.ConfigureRegionAdapterMappings();
            if (mappings == null) return null;

            var fluentRibbonRegionAdapter = ServiceLocator.Current.GetInstance<RibbonRegionAdapter>();
            mappings.RegisterMapping(typeof(Fluent.Ribbon), fluentRibbonRegionAdapter);

            var stackPanelRegionAdapter = ServiceLocator.Current.GetInstance<StackPanelRegionAdapter>();
            mappings.RegisterMapping(typeof(StackPanel), stackPanelRegionAdapter);

            return mappings;
        }

        protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
        {
            var behaviors = base.ConfigureDefaultRegionBehaviors();
            behaviors.AddIfMissing(DependentViewRegionBehavior.BehaviorKey, typeof(DependentViewRegionBehavior));
            return behaviors;
        }

        protected override DependencyObject CreateShell()
        {
            return new Shell();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();
            Application.Current.MainWindow = (Window)Shell;
            if (Application.Current.MainWindow != null) Application.Current.MainWindow.Show();
        }
    }
}

I have seen examples on the internet, but none specific to my MVVM needs, and most examples are fairly dated.  I am using CommonServiceLocator v2.0.4 and CommonServiceLocator.UnityAdapter v1.0.0.41670.



Rob E.

Get all Active or Alive or instantiated ViewModel...Without MVVMl Light or Third Party tools

$
0
0

var nav = SimpleIoc.Default.GetInstance<INavigationService>();

   SimpleIoc.Default.Register<MainViewModel>();                  
        SimpleIoc.Default.Register<SecondViewModel>(); 

Above Code Works Using MVVM Light.....But in my current Project no third Dll's Allowed....How Can I Achieve It..

MVVM : Not able to Access Properties of Child UserControl ...But Able to Access MainWindow.

$
0
0

MVVM : Not able to Access Properties  of Child UserControl ...But Able to Access MainWindow.

 var windows = Application.Current.Windows.OfType<Window>();

WPF Entity Framework Async

$
0
0

I am trying to return an observable collection to my WPF window.  If I get the data non async the collection is filled and notifies WPF via binding.  However if I fill the collection async, the collection is filled, but WPF doesn't seem to get notified.

I have seen that I should be able to use this bindingoperations.enablecollectionsynchronization, and all the examples show it being overloaded.

however when I call this method I do not get any overloads of this.  I am using .Net 4.6.1.

Any help would be appreciated on using this method OR how to have an observable collection notify my WPF once the collection has been filled async.

I am using Entity Frameworks LoadAsync method.

Thanks.


nlm


WPF Sql Error

$
0
0

My WPF app works fine when running, but AT design time I get this error:SeverityCodeDescriptionProjectFileLineSuppression State
ErrorA network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)UiMaintenanceOption.xaml14

Now the MaintenanceOption.xaml is a Window, with some UserControls that are in turn hooked up to a ViewModel.

I have Rem'd out all UserControls except for 1, so I can test, remd out the calls to the VM that load the data, cleaned my solution and rebuilt it (rebuilds fine) and I still get this error.

Any ideas on how to solve this would greatly be appreciated.  I have NO calls in the container Window calling the database.


nlm

ServiceLocationProvider must be set error

$
0
0

The following code compiles but fails at this line: "var fluentRibbonRegionAdapter = ServiceLocator.Current.GetInstance<RibbonRegionAdapter>();".

The error message is ' ServiceLocationProvider must be set.'

using CommonServiceLocator;
using Prism.Modularity;
using Prism.Regions;
using Prism.Unity;
using MyApp.Infrastructure.RegionAdapters;
using MyApp.Prism;
using MyApp.Views;
using System.Windows;
using System.Windows.Controls;

namespace MyApp.Startup
{
    public class Bootstrapper : UnityBootstrapper
    {

        protected override IModuleCatalog CreateModuleCatalog()
        {
            var catalog = new DirectoryModuleCatalog { ModulePath = @".\Modules" };
            return catalog;
        }

        protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
        {
            var mappings = base.ConfigureRegionAdapterMappings();
            if (mappings == null) return null;

            var fluentRibbonRegionAdapter = ServiceLocator.Current.GetInstance<RibbonRegionAdapter>();
            mappings.RegisterMapping(typeof(Fluent.Ribbon), fluentRibbonRegionAdapter);

            var stackPanelRegionAdapter = ServiceLocator.Current.GetInstance<StackPanelRegionAdapter>();
            mappings.RegisterMapping(typeof(StackPanel), stackPanelRegionAdapter);

            return mappings;
        }

        protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
        {
            var behaviors = base.ConfigureDefaultRegionBehaviors();
            behaviors.AddIfMissing(DependentViewRegionBehavior.BehaviorKey, typeof(DependentViewRegionBehavior));
            return behaviors;
        }

        protected override DependencyObject CreateShell()
        {
            return new Shell();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();
            Application.Current.MainWindow = (Window)Shell;
            if (Application.Current.MainWindow != null) Application.Current.MainWindow.Show();
        }
    }
}

I have seen examples on the internet, but none specific to my MVVM needs, and most examples are fairly dated.  I am using CommonServiceLocator v2.0.4 and CommonServiceLocator.UnityAdapter v1.0.0.41670.



Rob E.


WPF Combo Box issue in Windows 7 classic theme

$
0
0

We are using simple combo box control in our WPF window. This is a editable combo box (IsEditable property set to true) which have padding of "5,5,0,5". When we use this in windows 7 with classic theme, clicking on the empty space inside the combo box (Create by 5 pxl padding) will bring down the drop down. We don't want drop down to be opened from any action other than clicking toggle button. This issue is happening only in windows 7 with classic theme.

Does anybody faced this issue or have any solution?

Thanks

Shreeraj

ListView.SelectedItem.ToString() - Object reference not set to an ...

$
0
0

Hi all,

I have lot of similar problems.Can you help me to  solve this one?

MessageBox.Show("Name : " + listCars.SelectedItem.ToString());

So when I have  this  under button it shows  me an error >

>> Object reference not set to an instance of an object

I have no idea what to do with this ...thanks for help

Exception unhandeled:No information was found about this pixel format

$
0
0

Hello dear Programmers,

i am trzing to connect my kinect through out this code belwo. The code by it self doesnot dive any errors,

but when I am connecting the kinect it gives me then "unhandeled exception" on the line

(int stride = width * format.BitsPerPixel / 8;)

I have searched a lot, but I didn't understand how to fix it. can you please help me.

Thanks,

Houssam

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 Microsoft.Kinect; using System.IO; namespace WpfApp5 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Array pixels; public MainWindow() { InitializeComponent(); KinectSensor _sensor; MultiSourceFrameReader _reader; _sensor = KinectSensor.GetDefault(); if (_sensor != null) { _sensor.Open(); } _reader = _sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.Infrared); _reader.MultiSourceFrameArrived += Reader_MultiSourceFrameArrived; void Reader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e) { // Get a reference to the multi-frame var reference = e.FrameReference.AcquireFrame(); // Open color frame using (var frame = reference.ColorFrameReference.AcquireFrame()) { if (frame != null) { // Do something with the frame... camera.Source = ToBitmap(frame); } } // Open depth frame using (var frame2 = reference.DepthFrameReference.AcquireFrame()) { if (frame2 != null) { // Do something with the frame... camera.Source = ToBitmap2(frame2); } } // Open infrared frame using (var frame1 = reference.InfraredFrameReference.AcquireFrame()) { if (frame1 != null) { // Do something with the frame... camera.Source = ToBitmap3(frame1); } } } ImageSource ToBitmap(ColorFrame frame) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; byte[] pixels = new byte[width * height * ((PixelFormats.Bgr32.BitsPerPixel + 7) / 8)]; if (frame.RawColorImageFormat == ColorImageFormat.Bgra) { frame.CopyRawFrameDataToArray(pixels); } else { frame.CopyConvertedFrameDataToArray(pixels, ColorImageFormat.Bgra); } PixelFormat format = new PixelFormat(); int stride = width * format.BitsPerPixel / 8; return BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride); } ImageSource ToBitmap2(DepthFrame frame) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; ushort minDepth = frame.DepthMinReliableDistance; ushort maxDepth = frame.DepthMaxReliableDistance; ushort[] depthData = new ushort[width * height]; byte[] pixelData = new byte[width * height * (PixelFormats.Bgr32.BitsPerPixel + 7) / 8]; frame.CopyFrameDataToArray(depthData); int colorIndex = 0; for (int depthIndex = 0; depthIndex < depthData.Length; ++depthIndex) { ushort depth = depthData[depthIndex]; byte intensity = (byte)(depth >= minDepth && depth <= maxDepth ? depth : 0); pixelData[colorIndex++] = intensity; // Blue pixelData[colorIndex++] = intensity; // Green pixelData[colorIndex++] = intensity; // Red++colorIndex; } PixelFormat format = new PixelFormat(); int stride = width * format.BitsPerPixel / 8; return BitmapSource.Create(width, height, 96, 96, format, null, pixelData, stride); } } private ImageSource ToBitmap3(InfraredFrame frame) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; ushort[] infraredData = new ushort[width * height]; byte[] pixelData = new byte[width * height * (PixelFormats.Bgr32.BitsPerPixel + 7) / 8]; frame.CopyFrameDataToArray(infraredData); int colorIndex = 0; for (int infraredIndex = 0; infraredIndex < infraredData.Length; ++infraredIndex) { ushort ir = infraredData[infraredIndex]; byte intensity = (byte)(ir >> 8); pixelData[colorIndex++] = intensity; // Blue pixelData[colorIndex++] = intensity; // Green pixelData[colorIndex++] = intensity; // Red++colorIndex; } PixelFormat format = new PixelFormat(); int stride = width * format.BitsPerPixel / 8; return BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride); } private void ColorButton_Click(object sender, RoutedEventArgs e) { } private void DepthButton_Click(object sender, RoutedEventArgs e) { } private void InfraredButton_Click(object sender, RoutedEventArgs e) { } } }


Viewing all 18858 articles
Browse latest View live


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