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

TextBlock ActualWidth Wrong When Smaller Than Text

$
0
0

Hello,

Im trying to make a control like TextBlock but when the width of the control is smaller than the text, the control will have a transparent gradient.

It works well when i set the Width of the control, but when i set the Width to nothing(auto), it doesnt work.

I found that the problem is when you have a TextBlock with the width set to auto, the ActualWidth property works as expected, until the TextBlock is smaller than the text, and then instead of giving the rendered width of the control, it gives you the rendered width of the control before it was smaller than the text.

<Grid Width="100"><TextBlock x:Name="textBlock" Text="Sample text"/></Grid>

textBlock.ActualWidth = 100



<Grid Width="50"><TextBlock x:Name="textBlock" Text="Sample text"/></Grid>

textBlock.ActualWidth = 62.256666666667

**NOTE: this happens only if the TextBlock's TextTrimming property is set to None and the TextWrapping property is set to NoWrap**

My question is: is there a different property or way i can get the TextBlock's actual ActualWidth?

Thanks,


~Tamir


How to access control from paricular datatemplate of list view

$
0
0

I have list view like this

<ListView Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding DailyVCRModel.HistoryListCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Margin="0,0,0,0" x:Name="vcrListView" ScrollViewer.VerticalScrollBarVisibility="Auto" Height="370" Width="1000" HorizontalAlignment="Center" KeyboardNavigation.TabNavigation="Continue"><ListView.ItemContainerStyle><Style TargetType="ListViewItem"><Setter Property="HorizontalContentAlignment" Value="Stretch" /><Style.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="Background" Value="{x:Null}" /><Setter Property="BorderBrush" Value="{x:Null}" /></Trigger><Trigger Property="IsMouseOver" Value="True"><Setter Property="Focusable" Value="False" /><Setter Property="Background" Value="White"></Setter></Trigger></Style.Triggers></Style></ListView.ItemContainerStyle><ListView.View><GridView><GridViewColumn Header="" Width="420" DisplayMemberBinding="{Binding InspectionTypes}"></GridViewColumn><GridViewColumn Header="Fail" Width="80"><GridViewColumn.CellTemplate><DataTemplate><Button x:Name="failButton" BorderBrush="Transparent" BorderThickness="0" Background="Transparent" Width="45"><Image Name="img11" Source="{Binding FailImage,Mode=TwoWay}"/><Button.Style><Style TargetType="Button"><Style.Triggers><Trigger Property="Button.IsFocused" Value="True"><Setter Property="Background" Value="White" /></Trigger></Style.Triggers></Style></Button.Style><ie:Interaction.Triggers><ie:EventTrigger EventName="Click"><ie:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView},Path=DataContext.FailImageButtonCommand}"

CommandParameter="{Binding ElementName=failButton}"><!--<ie:InvokeCommandAction.CommandParameter><MultiBinding ><MultiBinding.Converter><app:VCRChecklistConverter/></MultiBinding.Converter><Binding ElementName="{Binding ElementName=passButton}"/></MultiBinding></ie:InvokeCommandAction.CommandParameter>--></ie:InvokeCommandAction></ie:EventTrigger></ie:Interaction.Triggers></Button></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Pass" Width="80"><GridViewColumn.CellTemplate><DataTemplate x:Name="mySecondItemTemplate"><Button x:Name="passButton" BorderBrush="Transparent" BorderThickness="0" Background="Transparent" Width="45"><Image Name="img12" Source="{Binding PassImage, Mode=TwoWay}"/><Button.Style><Style TargetType="Button"><Style.Triggers><Trigger Property="Button.IsFocused" Value="True"><Setter Property="Background" Value="White" /></Trigger></Style.Triggers></Style></Button.Style><ie:Interaction.Triggers><ie:EventTrigger EventName="Click"><ie:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView},

Path=DataContext.PassImageButtonCommand}"

CommandParameter="{Binding ElementName=passButton}"><!--<ie:InvokeCommandAction.CommandParameter><MultiBinding ><MultiBinding.Converter><app:VCRChecklistConverter/></MultiBinding.Converter><Binding ElementName="{Binding ElementName=passButton}"/></MultiBinding></ie:InvokeCommandAction.CommandParameter>--></ie:InvokeCommandAction></ie:EventTrigger></ie:Interaction.Triggers></Button></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Comment" Width="340"><GridViewColumn.CellTemplate><DataTemplate><TextBox Width="300" Text="{Binding Comment, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Name="commentTextBox"/></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridView.ColumnHeaderContainerStyle><Style TargetType="GridViewColumnHeader"><Setter Property="FontWeight" Value="Bold" /><Setter Property="HorizontalContentAlignment" Value="Center"></Setter></Style></GridView.ColumnHeaderContainerStyle></GridView></ListView.View></ListView>

I want to access control of  grid view column by name  of any column . When i am trying by this method-

   ListViewItem row = ((ListViewItem)listView.ItemContainerGenerator.ContainerFromIndex(index));
                ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(row);
                DataTemplate template = myContentPresenter.ContentTemplate;

                Button failButton = (template.FindName("failButton", myContentPresenter) as Button);
Above method only working for first data Template. Can i find control from any data template of column. Please provide solution.




presentationhost.exe running at 50% CPU

$
0
0

Hi,

We have one user that is seeing high CPU usage with presentationhost.exe when running our WPF app. The user starts the WPF app, the CPU goes immediately to 50% and the UI hangs. This is happening on just one laptop running XP.

I got the user to run adplus -hang and this is the call stack of the thread that is using the CPU. it looks like the problem might be in wpfgfx_v0300.dll

Thanks for looking...

Brian



0:000> !runaway
 User Mode Time
  Thread       Time
  15:15c0      0 days 0:01:57.656
   0:12b4      0 days 0:00:00.843
  14:158c      0 days 0:00:00.015
  13:1584      0 days 0:00:00.000
  12:1580      0 days 0:00:00.000
  11:14f8      0 days 0:00:00.000
  10:14f4      0 days 0:00:00.000
   9:14ec      0 days 0:00:00.000
   8:14e8      0 days 0:00:00.000
   7:1424      0 days 0:00:00.000
   6:1420      0 days 0:00:00.000
   5:130c      0 days 0:00:00.000
   4:1304      0 days 0:00:00.000
   3:1300      0 days 0:00:00.000
   2:12fc      0 days 0:00:00.000
   1:12f8      0 days 0:00:00.000
0:000> ~15e !dumpstack
OS Thread Id: 0x15c0 (15)
Current frame:  (JitHelp: CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE)
ChildEBP RetAddr  Caller,Callee
0579f0e8 578484c3 (MethodDesc 0x577c9d94 +0x13 MS.Internal.Invariant.Assert(Boolean)), calling  (JitHelp: CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE)
0579f0f0 547f6621 (MethodDesc 0x546a5fbc +0x31 MS.Internal.FontCache.ElementCacher.get_Mapping()), calling (MethodDesc 0x577c9d94 +0 MS.Internal.Invariant.Assert(Boolean))
0579f10c 547f6945 (MethodDesc 0x546a60d4 +0x35 MS.Internal.FontCache.HashTable.GetElementInfo(Int32* ByRef, ElementHeader* ByRef, MS.Internal.FontCache.CheckedPointer ByRef)), calling (MethodDesc 0x546a5fbc +0 MS.Internal.FontCache.ElementCacher.get_Mapping())
0579f134 547f677a (MethodDesc 0x546a6140 +0xaa MS.Internal.FontCache.HashTable.Lookup(MS.Internal.FontCache.IFontCacheElement, Boolean)), calling (MethodDesc 0x546a60d4 +0 MS.Internal.FontCache.HashTable.GetElementInfo(Int32* ByRef, ElementHeader* ByRef, MS.Internal.FontCache.CheckedPointer ByRef))
0579f160 792d9963 (MethodDesc 0x7910eb1c +0x13 System.SZArrayHelper.get_Item[[System.UInt16, mscorlib]](Int32)), calling mscorwks!JIT_IsInstanceOfArray
0579f174 547feb27 (MethodDesc 0x546a8b58 +0x277 MS.Internal.FontCache.FontCacheAccessor.GetGlyphs(MS.Internal.FontCache.BaseGlyphElement, System.Collections.Generic.IList`1<UInt16>, Void*[])), calling (MethodDesc 0x546a6140 +0 MS.Internal.FontCache.HashTable.Lookup(MS.Internal.FontCache.IFontCacheElement, Boolean))
0579f1bc 547fe7a7 (MethodDesc 0x54617644 +0xd7 MS.Internal.FontCache.FontCacheAccessor.GetBitmaps(System.String, Int32, Int32, Int32, UInt16, UInt16, UInt16, Int32, UInt16[], Void*[])), calling (MethodDesc 0x546a8b58 +0 MS.Internal.FontCache.FontCacheAccessor.GetGlyphs(MS.Internal.FontCache.BaseGlyphElement, System.Collections.Generic.IList`1<UInt16>, Void*[]))
0579f1f0 547fe682 (MethodDesc 0x54617638 +0x82 MS.Internal.FontCache.FontCacheAccessor.CreateGlyphBitmapsHelper(IntPtr, FontFaceID, UInt16[], UInt32)), calling (MethodDesc 0x54617644 +0 MS.Internal.FontCache.FontCacheAccessor.GetBitmaps(System.String, Int32, Int32, Int32, UInt16, UInt16, UInt16, Int32, UInt16[], Void*[]))
0579f240 547fe580 (MethodDesc 0x5461762c +0xa0 MS.Internal.FontCache.FontCacheAccessor.CreateGlyphsAtRenderTime(IntPtr, IntPtr, UInt16)), calling (MethodDesc 0x54617638 +0 MS.Internal.FontCache.FontCacheAccessor.CreateGlyphBitmapsHelper(IntPtr, FontFaceID, UInt16[], UInt32))
0579f26c 547fe482 (MethodDesc 0x546a8ae4 +0x42 MS.Internal.FontCache.FontCacheAccessor.CreateGlyphsCallback(IntPtr, IntPtr, UInt16)), calling (MethodDesc 0x5461762c +0 MS.Internal.FontCache.FontCacheAccessor.CreateGlyphsAtRenderTime(IntPtr, IntPtr, UInt16))
0579f29c 79e71b4c mscorwks!CallDescrWorker+0x33
0579f2b0 79e821b1 mscorwks!CallDescrWorkerWithHandler+0xa3, calling mscorwks!CallDescrWorker
0579f330 79fa987a mscorwks!ForwardCallToManagedMethod+0x55, calling mscorwks!CallDescrWorkerWithHandler
0579f350 79fa9a32 mscorwks!DoUMThunkCallWorker+0x1de, calling mscorwks!ForwardCallToManagedMethod
0579f3e4 79e79cba mscorwks!ClrFlsSetValue+0x57, calling mscorwks!_EH_epilog3
0579f41c 79fd8733 mscorwks!Thread::EnterContextRestricted+0x21d, calling mscorwks!_EH_epilog3
0579f44c 7a0c9b40 mscorwks!DoUMThunkCall+0x1e8, calling mscorwks!DoUMThunkCallWorker
0579f4d0 4fe7341e d3d9!CD3DDDIDX9::SurfaceBlt+0xe, calling d3d9!CD3DDDIDX6::GetHalBufferPointer
0579f52c 003c607d 003c607d, calling mscorwks!DoUMThunkCall
0579f55c 540343e4 wpfgfx_v0300!CMilSlaveGlyphCache::EnsureGlyphBitmapsArePresent+0x5d
0579f57c 540343e4 wpfgfx_v0300!CMilSlaveGlyphCache::EnsureGlyphBitmapsArePresent+0x5d
0579f5e0 54031df7 wpfgfx_v0300!CGlyphRunResource::CreateRealization+0x1bf, calling wpfgfx_v0300!CMilSlaveGlyphCache::EnsureGlyphBitmapsArePresent
0579f610 54032289 wpfgfx_v0300!CGlyphRunResource::GetAvailableScale+0x1a0, calling wpfgfx_v0300!CGlyphRunResource::CreateRealization
0579f644 4fe52ba5 d3d9!CD3DBase::SetTransform+0xb5, calling ntdll!RtlLeaveCriticalSection
0579f68c 54031063 wpfgfx_v0300!CBaseGlyphRunPainter::Init+0x1ad, calling wpfgfx_v0300!CGlyphRunResource::GetAvailableScale
0579f6d4 54037c69 wpfgfx_v0300!CD3DGlyphRunPainter::Paint+0xa9, calling wpfgfx_v0300!CBaseGlyphRunPainter::Init
0579f6f0 540501b9 wpfgfx_v0300!CD3DDeviceLevel1::SetSurfaceToClippingMatrix+0xc4, calling wpfgfx_v0300!CHwRenderStateManager::Set2DTransformForFixedFunction
0579f708 54055a54 wpfgfx_v0300!CD3DDeviceLevel1::SetClipRect+0x17b, calling wpfgfx_v0300!CCodeTracer::IsTracingEnabled
0579f770 540374fd wpfgfx_v0300!CHwSurfaceRenderTarget::DrawGlyphs+0x191, calling wpfgfx_v0300!CD3DGlyphRunPainter::Paint
0579f844 5400d780 wpfgfx_v0300!CBrushRealizer::CBrushRealizer+0x48, calling wpfgfx_v0300!CMilAlphaMaskWrapper::SetVisualPreviousOuterBounds
0579f864 540129ea wpfgfx_v0300!CBrushRealizer::CreateResourceRealizer+0x44
0579f8a8 7818efed msvcr80!_handle_exc+0x1d2, calling msvcr80!_set_statfp
0579f8d0 78190ff7 msvcr80!_87except+0xc4, calling msvcr80!_ctrlfp
0579f8e4 5400f7b4 wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::Intersect+0x6f, calling wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::IsEmpty
0579f8e8 5400e8da wpfgfx_v0300!CMetaIterator::SetupForNextInternalRT+0x1ce, calling wpfgfx_v0300!CDisplaySet::GetDisplaySettings
0579f8fc 54013318 wpfgfx_v0300!CMetaIterator::CMetaIterator+0x47, calling wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::IsEmpty
0579f914 540375a4 wpfgfx_v0300!CHwDisplayRenderTarget::DrawGlyphs+0x1c, calling wpfgfx_v0300!CHwSurfaceRenderTarget::DrawGlyphs
0579f928 54030778 wpfgfx_v0300!CMetaRenderTarget::DrawGlyphs+0xb6
0579f958 54012418 wpfgfx_v0300!CDrawingContext::DrawRectangle+0x102, calling wpfgfx_v0300!CCodeTracer::IsTracingEnabled
0579f990 5400d359 wpfgfx_v0300!CBaseMatrix::Transform2DBounds+0x5f, calling wpfgfx_v0300!CBaseMatrix::Transform
0579f9e0 54030683 wpfgfx_v0300!CDrawingContext::DrawGlyphRun+0x1de
0579fa38 540124f0 wpfgfx_v0300!CMilSlaveRenderData::Draw+0x4a4
0579fa80 54012040 wpfgfx_v0300!InflateRectF_InPlace+0xb, calling wpfgfx_v0300!InflateRectF_InPlace
0579fa84 5400f7b4 wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::Intersect+0x6f, calling wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::IsEmpty
0579fa88 5400f816 wpfgfx_v0300!CDrawingContext::GetClippedWorldSpaceBounds+0x5c, calling wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::Intersect
0579faac 54010f74 wpfgfx_v0300!CSnappingFrame::PushFrame+0x89, calling wpfgfx_v0300!CSnappingFrameEmpty::PushFrame
0579fadc 54012562 wpfgfx_v0300!CMilVisual::RenderContent+0x2a, calling wpfgfx_v0300!CMilSlaveRenderData::Draw
0579faf4 5400f950 wpfgfx_v0300!CDrawingContext::PreSubgraph+0x485
0579fb6c 540156f1 wpfgfx_v0300!CMetaRenderTarget::Clear+0x129, calling wpfgfx_v0300!CMetaIterator::~CMetaIterator
0579fbc4 540105da wpfgfx_v0300!CWatermarkStack<CModelWalker::CFrame,64,2,10>::Push+0xdf
0579fbd8 54009f0d wpfgfx_v0300!CPtrArrayBase::operator[]+0x7, calling wpfgfx_v0300!CPtrMultisetBase::GetCount
0579fbdc 5400f6c5 wpfgfx_v0300!CMilVisual::GetChildAt+0x21, calling wpfgfx_v0300!CPtrArrayBase::operator[]
0579fbec 5400f725 wpfgfx_v0300!CGraphWalker::GotoFirstChild+0x61
0579fc0c 5400e646 wpfgfx_v0300!CGraphIterator::Walk+0x32
0579fc34 5400f622 wpfgfx_v0300!CDrawingContext::DrawVisualTree+0x324, calling wpfgfx_v0300!CGraphIterator::Walk
0579fc48 54015b24 wpfgfx_v0300!CPreComputeContext::ConvertInnerToOuterBounds+0xbf, calling wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::IsWellOrdered
0579fcd0 54009f0d wpfgfx_v0300!CPtrArrayBase::operator[]+0x7, calling wpfgfx_v0300!CPtrMultisetBase::GetCount
0579fcd4 5400f6c5 wpfgfx_v0300!CMilVisual::GetChildAt+0x21, calling wpfgfx_v0300!CPtrArrayBase::operator[]
0579fcdc 54009f0d wpfgfx_v0300!CPtrArrayBase::operator[]+0x7, calling wpfgfx_v0300!CPtrMultisetBase::GetCount
0579fce0 5400f6c5 wpfgfx_v0300!CMilVisual::GetChildAt+0x21, calling wpfgfx_v0300!CPtrArrayBase::operator[]
0579fcf0 5400f688 wpfgfx_v0300!CGraphWalker::GotoSibling+0x4f
0579fd00 5400eba9 wpfgfx_v0300!CGraphWalker::EndWalk+0x12, calling wpfgfx_v0300!CWatermarkStack<CModelWalker::CFrame,64,2,10>::Optimize
0579fd08 5400ebc1 wpfgfx_v0300!CGraphIterator::Walk+0x110, calling wpfgfx_v0300!CGraphWalker::EndWalk
0579fd30 5400ecb2 wpfgfx_v0300!CPreComputeContext::PreCompute+0xfc, calling wpfgfx_v0300!CWatermarkStack<TMilRect_<float,MilRectF,MilPointAndSizeF,RectUniqueness::NotNeeded>,8,2,8>::Clear
0579fd44 5400ecfa wpfgfx_v0300!CDrawingContext::PreCompute+0x52, calling wpfgfx_v0300!CPreComputeContext::PreCompute
0579fd5c 5400eef8 wpfgfx_v0300!CDirtyRegion2::GetDirtyRegion+0x3b, calling msvcr80!memset
0579fd68 5400ef14 wpfgfx_v0300!CDirtyRegion2::GetDirtyRegion+0x57, calling wpfgfx_v0300!TMilRect<float,MilRectF,RectUniqueness::NotNeeded>::IsEmpty
0579fd80 540302f6 wpfgfx_v0300!CDrawingContext::Render+0x324, calling wpfgfx_v0300!CDrawingContext::DrawVisualTree
0579fda0 54007231 wpfgfx_v0300!CDisplaySet::HasDisplayStateChanged+0x10, calling wpfgfx_v0300!CDisplaySet::IsUpToDate
0579fdfc 5400c019 wpfgfx_v0300!CSlaveHWndRenderTarget::Render+0x209, calling wpfgfx_v0300!CDrawingContext::Render
0579fe54 540076e0 wpfgfx_v0300!FreeBatch+0x14, calling wpfgfx_v0300!COcclusionContext::`scalar deleting destructor'
0579fe60 54007391 wpfgfx_v0300!CComposition::ProcessCommandBatch+0x22d6, calling wpfgfx_v0300!FreeBatch
0579fea8 540073c4 wpfgfx_v0300!CComposition::ProcessPartitionCommand+0x70, calling wpfgfx_v0300!CComposition::ProcessCommandBatch
0579febc 5400be78 wpfgfx_v0300!CRenderTargetManager::Render+0x2e
0579fedc 54007523 wpfgfx_v0300!CComposition::Render+0x21, calling wpfgfx_v0300!CRenderTargetManager::Render
0579fef4 540075d6 wpfgfx_v0300!CComposition::ProcessComposition+0xf3, calling wpfgfx_v0300!CComposition::Render
0579ff20 5400700e wpfgfx_v0300!CPartitionManager::LogEvent+0x26, calling kernel32!InterlockedCompareExchange
0579ff2c 5400700e wpfgfx_v0300!CPartitionManager::LogEvent+0x26, calling kernel32!InterlockedCompareExchange
0579ff34 5400700e wpfgfx_v0300!CPartitionManager::LogEvent+0x26, calling kernel32!InterlockedCompareExchange
0579ff38 5400700e wpfgfx_v0300!CPartitionManager::LogEvent+0x26, calling kernel32!InterlockedCompareExchange
0579ff58 54007667 wpfgfx_v0300!CComposition::Compose+0x3e, calling wpfgfx_v0300!CComposition::ProcessComposition
0579ff6c 540076a2 wpfgfx_v0300!CPartitionThread::RenderPartition+0x1c
0579ff88 5400717b wpfgfx_v0300!CPartitionThread::Run+0x48, calling wpfgfx_v0300!CPartitionThread::RenderPartition
0579ff9c 5400b68e wpfgfx_v0300!CPartitionThread::ThreadMain+0x1e
0579ffa0 79e8209e mscorwks!Module::EnsureActive+0x5f, calling mscorwks!DomainFile::EnsureLoadLevel
0579ffb4 7c80b729 kernel32!BaseThreadStart+0x37
0579ffbc 79e8209e mscorwks!Module::EnsureActive+0x5f, calling mscorwks!DomainFile::EnsureLoadLevel

Is it possible to invoke Command not from Button?

$
0
0

I have DataGrid with DataTemplate:

<DataGrid ItemsSource="{Binding Persons}" Grid.Row="1" AutoGenerateColumns="False"><DataGrid.Columns><DataGridTextColumn Binding="{Binding IdPerson}"><DataGridTextColumn.HeaderTemplate><DataTemplate><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Button DataContext="{Binding Path=Data, Source={StaticResource proxy}}"
Command="{Binding DataContext.HelloCommand, RelativeSource={RelativeSource
AncestorType=Window}}"/><TextBlock Grid.Row="1" HorizontalAlignment="Center" Text = "{Binding
DataContext.Hello, RelativeSource={RelativeSource AncestorType=DataGrid}}"/></Grid></DataTemplate></DataGridTextColumn.HeaderTemplate></DataGridTextColumn><DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}"/><DataGridTextColumn Header="LastName" Binding="{Binding LastName}"/></DataGrid.Columns></DataGrid> 
Is it possible when user clicks at any place(in scope of HeaderTemplate) of DataTemplate to invoke Command="{Binding DataContext.HelloCommand, RelativeSource={RelativeSource AncestorType=Window}}" of Button?

Why is the rich text editor so poorly done?

$
0
0
I have spent the better part of a day trying to get my rich text editor to work properly.  I add Bold, Italic, and Underline buttons and associated the EditingCommands to them.  The EditingCommands work fine when I use the keyboard, but when I press the button, it does not work.  I have tried to programmatically code for pressing the button, but nothing seems to work.  I tried to send the EditingCommand to the rich text editor, but this did not work at all.  I tried setting the FontWeight and Style, but there were issues here as well.... and forget about underline since the rich text editor doesn't have a TextDecoration property.  When I set the font weight and style, whenever I change them, it changes everything.  Whenever I try to apply it to whatever is selected, it applies it to what isn't selected.  I even tried to use the WPF Toolkit and this didn't solve any of my issues.  This is beyond frustrating and IMO, Microsoft needs to take a look at this control and rewrite it.

RadioButton IsChecked Binding not sending uncheck event

$
0
0

I am trying to databind several radiobuttons to some objects that have a checked property. If a click on an unselected radio button, my databound object is updated. However the other object that should now be not checked is not. The code is fairly simple.

Am I missing something here or is this a bug in databinding for RadioButtons?

<

Windowx:Class="RadioTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Radio Button Test"Height="154"Width="285">

<

StackPanelMargin="5">

<

RadioButtonName="A"IsChecked="{Binding Path=Checked}"GroupName="Group">Yes</RadioButton>

<

RadioButtonName="B"IsChecked="{Binding Path=Checked}"GroupName="Group">No</RadioButton>

<

CheckBoxName="C"IsChecked="{Binding Path=Checked}">Yes</CheckBox>

<

CheckBoxName="D"IsChecked="{Binding Path=Checked}">No</CheckBox>

</

StackPanel>

</

Window>

publicpartialclassRadioTest : System.Windows.Window

{

MyData _Yes = newMyData();

MyData _No = newMyData();

public RadioTest()

{

InitializeComponent();

_Yes.Checked =

true;

A.DataContext = _Yes;

C.DataContext = _Yes;

B.DataContext = _No;

D.DataContext = _No;

}

}

publicclassMyData : INotifyPropertyChanged

{

privatebool _Checked;

publicbool Checked

{

get { return _Checked; }

set

{

_Checked =

value;

OnPropertyChanged(

"Checked");

}

}

 

#region

INotifyPropertyChanged Members

publiceventPropertyChangedEventHandler PropertyChanged;

protectedvoid OnPropertyChanged(string propertyName)

{

if (PropertyChanged != null)

{

PropertyChanged(

this, newPropertyChangedEventArgs(propertyName));

}

}

#endregion

}

}

how access the viewmodel of a new view

$
0
0

Hello all, 

I am new to MVVM. I start to play around and here is a first problem I run into: 

From the MainView I want to open another View an set a property of the corresponding ViewModel to something. I don't now how to access the ViewModel of the newly opened View. 

To be sure that you got my problem: 

I have a class called "Project". In my MainView that opens when running my solution in VS2015 I have a listview bound to a list of Projects (this list is a property of the MainViewViewModel). When I click on one of the List Items I want to open the ProjectView that shows the details of the clicked Project. But how do I access the ProjectViewViewModel in order to set its Property Project that will then be accessible in the ProjectView. 

I hope this is clear enought ! Thanks a lot for any kind support !

Best regards, 

Fabianus


DataTrigger binded to property in ViewModel is not fired in the Button of DataGrid

$
0
0

DataContext is set like this:

<Window x:Class="wpf_Row_In_Datagrid.MainWindow"
...><Window.DataContext><local:MainWindowViewModel/></Window.DataContext>

I've created ControlTemplates:

<Window.Resources><ControlTemplate x:Key="imgNo" TargetType="{x:Type Control}"><Image Source="pack://application:,,,/Images/up.png"/></ControlTemplate><ControlTemplate x:Key="imgUp" TargetType="{x:Type Control}"><!--<TextBlock  Text="Up"/>--><Image Source="pack://application:,,,/Images/up.png"/></ControlTemplate><ControlTemplate x:Key="imgDown" TargetType="{x:Type Control}"><Image Source="pack://application:,,,/Images/downArrow.png"/></ControlTemplate><DataTemplate x:Key="ButtonOneDataTemplate"><Control x:Name="theControl" Template="{DynamicResource imgNo}" /><DataTemplate.Triggers><DataTrigger Binding="{Binding IsImageChanged}" Value="true"><Setter TargetName="theControl" Property="Template" Value="{DynamicResource imgUp}" /></DataTrigger><DataTrigger Binding="{Binding IsImageChanged}" Value="false"><Setter TargetName="theControl" Property="Template" Value="{DynamicResource imgDown}" /></DataTrigger></DataTemplate.Triggers></DataTemplate></WindowResources>

and Button in DataGrid which uses above ControlTemplates:

<DataGrid ItemsSource="{Binding Persons}" Grid.Row="1" AutoGenerateColumns="False"><DataGrid.Columns><DataGridTextColumn Binding="{Binding IdPerson}"><DataGridTextColumn.HeaderTemplate><DataTemplate><Border Background="Violet"><StackPanel><Button ContentTemplate="{StaticResource ButtonOneDataTemplate}"
                 Command="{Binding DataContext.HelloCommand, RelativeSource=
                  {RelativeSource AncestorType=Window}}"
                  CommandParameter="{Binding DataContext.Hello,
                RelativeSource={RelativeSource AncestorType=DataGrid}}"/></StackPanel></Border></DataTemplate></DataGridTextColumn.HeaderTemplate></DataGridTextColumn></DataGrid.Columns></DataGrid>   

MyViewModel:

public class MainWindowViewModel:ViewModelBase
{
    public RelayCommand HelloCommand { get; set; }
    public MainWindowViewModel()
    {
       LoadPersons();
       HelloCommand = new RelayCommand(SayHello);
    }

    int helloCounter = 0;
    private void SayHello(object obj)
    {
       if (helloCounter % 2 == 0)
          IsImageChanged = true;
       else
          IsImageChanged = false;
       helloCounter++;
    }


    private bool isImageChanged=true;
    public bool IsImageChanged
    {
       get { return isImageChanged; }
       set { isImageChanged = value;
             OnPropertyChanged("IsImageChanged");
           }
    }
}

What I want is when I click on the button <Button ContentTemplate="{StaticResource ButtonOneDataTemplate}"/>, then Template should be replaced to {DynamicResource imgDown} or {DynamicResource imgUp} . DataTrigger depends on IsImageChanged  value.

However, if I click on the Button, then DataTrigger is not fired(Controltemplates such as imgUpimgDown are not changed). How can I achieve this from my ViewModel?







How to assign an event handler for DataTemplate in code?

$
0
0

I try to dynamically create and assign a DataTemplate to a HeaderTemplate of DataGrid through code. To do this I have a method GetDatatemplate(string fromstring) that defines an XML literal and then uses this to create a DataTemplate. This works fine as long as I don't include the MouseLeftButtonDown event handler in the DataTemplate.

My DataTemplate saved in string variable StringHeaderTemplate:

private string StringHeaderTemplate =@"<DataTemplate><DataTemplate.Resources><ControlTemplate x:Key=""imgNo"" TargetType=""{x:Type Control}""><Image Source = ""pack://application:,,,/Images/upArrow.png"" /></ControlTemplate ><ControlTemplate x:Key=""imgUp"" TargetType=""{x:Type Control}""><Image Source = ""pack://application:,,,/Images/upArrow.png"" /></ControlTemplate ><ControlTemplate x:Key=""imgDown"" TargetType=""{x:Type Control}"" ><Image Source = ""pack://application:,,,/Images/downArrow.png"" /></ControlTemplate ></DataTemplate.Resources><Grid Background=""Transparent"" MouseLeftButtonDown=""Grid_MouseLeftButtonDown""><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Button Content=""Hello""/><TextBlock Grid.Row=""1"" HorizontalAlignment= ""Center"" Text = ""TextBlock"" /><CheckBox Grid.Row= ""2"" HorizontalAlignment= ""Center"" IsChecked= ""True"" /></Grid ></DataTemplate>";

And the method which gets DataTemplate:

private DataTemplate GetDatatemplate(string fromstring)
{
    ParserContext context = new ParserContext();
    context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
    context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
    return  (DataTemplate)XamlReader.Parse(fromstring, context);
}

Then I just apply this DataTemplate to HeaderTemplate of DataGrid:

DataTemplate dtCell = null;
DataTemplate dtHeader = null;
string dtString = string.Empty;
string dtHeaderString = string.Empty;
switch(Type.GetTypeCode(e.PropertyType))
{
   case TypeCode.String:
   dtString = StringTemplate.Replace("xxColumnxx", e.PropertyName);
   dtHeaderString=StringHeaderTemplate;
   break;
}
if(!string.IsNullOrEmpty(dtString))
{
   dtCell = GetDataTemplateForDataGrid(dtCellString);
   dtHeader = GetDataTemplateForDataGrid(dtHeaderString);
   DataGridTemplateColumn c = new DataGridTemplateColumn()
   {
      CellTemplate = dtCell,
      HeaderTemplate = dtHeader,
   };
   e.Column = c;
}

The event handler is really simple:

private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
   MessageBox.Show(DateTime.Now.ToString());
}

The exception I get is a XamlParseException that has an InnerException of type ArgumentException that says:

"Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."

Any ideas what to do?






WPF PropertyChange event handled by first listener class instance only

$
0
0

I'm facing a problem with handling PropertyChanged event by more than one listener class instances.

In the code below there are two instances of ViewModel class being defined as DataContext for the control.

The ViewModel class  has a member _cs1  of ConnectionState class  that raises PropertyChanged event.

This event is handled by ConnectionPropertyChanged() method in the ViewModel class. This method sets the Presence property. That property is a source of data binding for the Text property of the TextBox control in the XAML.

Running the code I can see that only first TextBox (x:Name="textBox") gets Text property updated by the ConnectionPropertyChanged() method, second TextBox's (x:Name="textBox1") Text property remains unchanged when the event fires.

I just always get the event handled ( ConnectionPropertyChanged() fires and the TextBox gets updated) by the first listening object only. Why?

How to make both textboxes getting updated by the underlying event while still having separate, dedicated DataContext object for each TextBox (this is just a model of the problem) ?

Just to mention, the event raises after all listening objects (ViewModel class instances defined in the XAML) are instantiated.

XAML:

<StackPanel><TextBox x:Name="textBox"Text="{Binding Presence}"><TextBox.DataContext><local:ViewModel/></TextBox.DataContext></TextBox><TextBox x:Name="textBox1"Text="{Binding Presence}"><TextBox.DataContext><local:ViewModel/></TextBox.DataContext></TextBox></StackPanel>

ViewModel class:

classViewModel:ObservableObject{ConnectionState _cs1;publicViewModel(){Presence="";
        _cs1 =newConnectionState();
        _cs1.PropertyChanged+=ConnectionPropertyChanged;}privatestring presence ="";publicstringPresence{set{
                presence = value;RaisePropertyChanged("Presence");}
            get{return presence;}}publicvoidConnectionPropertyChanged(object sender,PropertyChangedEventArgs e){Presence= _cs1.CurrentState;}}

ObservableObject class implements INotifyPropertyChanged and is defined as in MicroMVVM framework 

ConnectionState class:

publicclassConnectionState:INotifyPropertyChanged{privateSocketState currentState =SocketState.Initial;publicSocketStateCurrentState{
        get {return currentState;}set{
            currentState = value;OnPropertyChanged();}}publiceventPropertyChangedEventHandlerPropertyChanged;protectedvoidOnPropertyChanged([CallerMemberName]string propertyName =""){PropertyChangedEventHandler handler =PropertyChanged;if(handler !=null){
            handler(this,newPropertyChangedEventArgs(propertyName));}}}

How to set default value in grid combobox ?

$
0
0

Hi .

I have a method which populate grid Combobox . I want to set its default value as we do perivously by using cmbobj.selectedindex = 0;  I have written my code , please help me. 

i dont find any default method or property which can set my default value in combo.!!!!

// Combo Calling code

dgattendance.Columns.Insert(i + 1, GetNewComboBoxColumn(Convert.ToString(i + 1), "ID", leaveitems.DefaultView));

//********** Combo Genration  Method ************

  public DataGridColumn GetNewComboBoxColumn(string header,
                                            string bindingPath,
                                            object itemsSource)
        {
            DataGridComboBoxColumn comboBoxColumn = new DataGridComboBoxColumn();
            comboBoxColumn.Header = header;
            comboBoxColumn.SelectedValuePath = "ID";
            comboBoxColumn.DisplayMemberPath = "leave";
            Binding binding = new Binding();
            binding.Path = new PropertyPath(bindingPath);
            comboBoxColumn.SelectedValueBinding = binding;

            Binding itemsSourceBinding = new Binding();
            itemsSourceBinding.Source = itemsSource;
            BindingOperations.SetBinding(comboBoxColumn, DataGridComboBoxColumn.ItemsSourceProperty, itemsSourceBinding);
            return comboBoxColumn;
        }


Ali Muhammad

Auto scroll canvas on button click

$
0
0

Hello,

In my application, i have a very big canvas which has many child elements in it. I want to add a kind of play and pause button which will allow user to scroll the content of a canvas horizontally. The feature should work if i click mouse wheel button also.

How i can do this for a Canvas control? Thanks in advance.

Thanks,

IamHuM

Simple login and navigation - NavigationService is null

$
0
0

Hi, I'm a newbie to C# (and OOP), and trying to navigate from a simple login form to a second page/ window, but the navigation fails (NavigationService nav is null) - why?  what am I missing (and why).  Full code below:

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 YM_POS_20160229_0949
{    /// <summary>    /// Interaction logic for MainWindow.xaml    /// </summary>    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();        }        public void ClickLoginSubmitButton(object sender, RoutedEventArgs e)        {            // Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'            Dictionary<stringstring> errMsg = new Dictionary<stringstring>();            // declare variables            string varUserName;            string varUserPass;            //string nav;            // define the variables whilst trimming the values passed            varUserName = LoginUsername.Text.Trim();            varUserPass = LoginPassword.Password.Trim();            // ensure something has been submitted            if ((varUserPass == ""&& (varUserName == ""))            {                errMsg.Add("Username""Username cannot be blank");                errMsg.Add("Password""Username cannot be blank");            }            else            {                // validate user name & password            }            if (errMsg.Count > 0)            {                // display the errors in a message box                MessageBox.Show("The following errors occurred: ");            }            else            {                // check the values submitted and make DB, HTML etc safe using a regex                if (errMsg.Count > 0)                {                    // display errors in a message box                    MessageBox.Show("The following errors occurred:");                }                else                {                    // logic in here to complete the logging in process                    // 1. attempt to connect to the database; if DB unavailable, error & break else go to 2.                    // 2. get the users' status where the username and password match                    // 2a. if the users' status is missing i.e., incorrect username;                    // errMsg.Add("UserCredentials","Supplied user credentials are incorrect");                    // 2b. else                    // switch based on the users status                    // if there are no errors, navigate to the users dashboard (aka Page1)                    NavigationService nav = NavigationService.GetNavigationService(new Page1());                    // check if the nav variable is populated                    if (nav != null)                    {                        nav.Navigate(nav);                    }                    else                    {                        // display an error message to the user advising them an error has occurred and Page1 is not available                        MessageBox.Show("An error has occured.  unable to proceed to " + nav);                    }                }            }        }    }
}

Thanks

Matt

TreeViewItem Templates and HorizontalAlignment

$
0
0

I have an application that is using a TreeView to present a list of items, grouped by date. The TreeView control is contained within a sizable grid column. When I resize the column of the grid, I want the width of the "child" items in the TreeView to stretch to fill the entire width of the grid column. The TreeView is configured to apply a different template to the selected "child" item using a Trigger, and that item does exactly what I want (stretches to fill the grid column width), however all of the unselected "child" items do not.

With no child item selected, child items not stretching to fill column width (gap on right side):

TreeView - No

Selecting a child item causes that child item to stretch to fill column width (no gap):

TreeView - First

The current state is achieved using the following basic code:

<ContentControl … ><ContentControl.Resources><ResourceDictionary><!-- Tree item look when it is selected --><ContentControl x:Key="TreeItemDataSelected" HorizontalAlignment="Stretch" VerticalAlignment="Top" ><Border Margin="10,3,3,3" BorderThickness="1" ><!-- control definition removed for brevity --></Border></ContentControl><Style x:Key="OurTreeViewStyle" TargetType="TreeViewItem"><Style.Triggers><Trigger Property="IsSelected" Value="true"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="TreeViewItem"><ContentControl Content="{StaticResource ResourceKey=TreeItemDataSelected}" /></ControlTemplate></Setter.Value></Setter></Trigger></Style.Triggers></Style></ResourceDictionary></ContentControl.Resources><TreeView Name="tvRunHistories" VerticalContentAlignment="Top" ><TreeView.Resources><HierarchicalDataTemplate DataType="{x:Type self:RunHistory}" ItemsSource="{Binding Members}" ItemContainerStyle="{StaticResource ResourceKey=OurTreeViewStyle}"><!-- display date at "root" nodes -->
<StackPanel Orientation="Horizontal" Margin="0,5,0,5" ><!-- definition removed for brevity --></StackPanel></HierarchicalDataTemplate><DataTemplate DataType="{x:Type self:RunHistoryItem}" ><Border Margin="-10,3,3,3" BorderThickness="1" HorizontalAlignment="Stretch"><!-- control definition removed for brevity – same basic content as TreeItemDataSelected ContentControl above --></Border></DataTemplate></TreeView.Resources></TreeView></ContentControl>

The problem seems to be that the "DataTemplate" content does not honor the HorizontalAlignment setting, but for selected items, when the Template gets changed to TreeItemDataSelected, its HorizontalAlignment setting is honored.

I have tried setting up an additional trigger to apply a different template when IsSelected is false, but that did not have the desired effect. I also tried enclosing the DataTemplate <Border> control inside a <ContentControl> and setting HorizontalAlignment of the <ContentControl> to Stretch, with no effect.

Any ideas on how to get unselected child items to stretch like the selected item does?


Checkbox loses its V on MouseUp (in grids only)

$
0
0

Hello again.

I have checkbox columns inside grids.

I'm using DataGridCheckBoxColumn and DataGridTemplateColumn, in order to place the
CheckBox style inside and fire events when Clicked.

The CheckBox won't click, or in other words - the V is checked as long as the Mouse is Down.

As soon as I pull the click up )MouseUp), if I'm inside the checkbox area, the V disappears.




I'm using style sheet for the CheckBox, can you see anything there that causes the
Checkbox to be unchecked when mouse up ?

It only happens in grids, when using checkboxes inside forms, they work fine !!!

HERE's the resource file for the CheckBox -

any help would be thanked !!!

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                    mc:Ignorable="d"><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="Shared.xaml" /></ResourceDictionary.MergedDictionaries><!-- Focus Visual --><Style x:Key="CheckBoxFocusVisual"><Setter Property="Control.Template"><Setter.Value><ControlTemplate><Border><Rectangle Margin="15,0,0,0"
                       StrokeThickness="1"
                       Stroke="#60000000"
                       StrokeDashArray="1 2" /></Border></ControlTemplate></Setter.Value></Setter></Style><!-- SimpleStyles: CheckBox --><Style x:Key="{x:Type CheckBox}"
         TargetType="{x:Type CheckBox}"><Setter Property="SnapsToDevicePixels"
            Value="true" /><Setter Property="OverridesDefaultStyle"
            Value="true" /><Setter Property="FocusVisualStyle"
            Value="{DynamicResource CheckBoxFocusVisual}" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type CheckBox}"><BulletDecorator Background="Transparent"><BulletDecorator.Bullet><Border x:Name="Border"
                      Width="30"
                      Height="30"
                      CornerRadius="0"
                      BorderThickness="1"><Border.BorderBrush><LinearGradientBrush StartPoint="0,0"
                                       EndPoint="0,1"><LinearGradientBrush.GradientStops><GradientStopCollection><GradientStop Color="{DynamicResource BorderLightColor}"
                                      Offset="0.0" /><GradientStop Color="{DynamicResource BorderDarkColor}"
                                      Offset="1.0" /></GradientStopCollection></LinearGradientBrush.GradientStops></LinearGradientBrush></Border.BorderBrush><Border.Background><LinearGradientBrush StartPoint="0,0"
                                       EndPoint="0,1"><LinearGradientBrush.GradientStops><GradientStopCollection><GradientStop Color="{DynamicResource ControlLightColor}" /><GradientStop Color="{DynamicResource ControlMediumColor}"
                                      Offset="1.0" /></GradientStopCollection></LinearGradientBrush.GradientStops></LinearGradientBrush></Border.Background><Grid><Path Visibility="Collapsed"
                        Width="10"
                        Height="10"
                        x:Name="CheckMark"
                        SnapsToDevicePixels="False"
                        StrokeThickness="2"
                        Data="M 10 5 L 5 10 M 5 10 L 0 0"><!--Data="M 0 0 L 7 7 M 0 7 L 7 0"--><!--"M 0 5 L 5 0 M 5 0 L 10 10"--><Path.Stroke><SolidColorBrush Color="{DynamicResource ControlDarkColor}" /><!--GlyphColor--></Path.Stroke></Path><Path Visibility="Collapsed"
                        Width="10"
                        Height="10"
                        x:Name="InderminateMark"
                        SnapsToDevicePixels="False"
                        StrokeThickness="2"><!--Data="M 0 7 L 7 0"--><Path.Stroke><SolidColorBrush Color="{DynamicResource GlyphColor}" /></Path.Stroke></Path></Grid></Border></BulletDecorator.Bullet><VisualStateManager.VisualStateGroups><VisualStateGroup x:Name="CommonStates"><VisualState x:Name="Normal" /><VisualState x:Name="MouseOver"><Storyboard><ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                  Storyboard.TargetProperty="(Panel.Background).
                        (GradientBrush.GradientStops)[1].(GradientStop.Color)"><EasingColorKeyFrame KeyTime="0"
                                           Value="{StaticResource ControlMouseOverColor}" /></ColorAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="Pressed"><Storyboard><ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                  Storyboard.TargetProperty="(Panel.Background).
                        (GradientBrush.GradientStops)[1].(GradientStop.Color)"><EasingColorKeyFrame KeyTime="0"
                                           Value="{StaticResource ControlPressedColor}" /></ColorAnimationUsingKeyFrames><ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                  Storyboard.TargetProperty="(Border.BorderBrush).
                        (GradientBrush.GradientStops)[0].(GradientStop.Color)"><EasingColorKeyFrame KeyTime="0"
                                           Value="{StaticResource PressedBorderDarkColor}" /></ColorAnimationUsingKeyFrames><ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                  Storyboard.TargetProperty="(Border.BorderBrush).
                        (GradientBrush.GradientStops)[1].(GradientStop.Color)"><EasingColorKeyFrame KeyTime="0"
                                           Value="{StaticResource PressedBorderLightColor}" /></ColorAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="Disabled" /></VisualStateGroup><VisualStateGroup x:Name="CheckStates"><VisualState x:Name="Checked"><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                   Storyboard.TargetName="CheckMark"><DiscreteObjectKeyFrame KeyTime="0"
                                              Value="{x:Static Visibility.Visible}" /></ObjectAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="Unchecked" /><VisualState x:Name="Indeterminate" /><!-- <VisualState x:Name="Indeterminate"><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                   Storyboard.TargetName="InderminateMark"><DiscreteObjectKeyFrame KeyTime="0"
                                              Value="{x:Static Visibility.Visible}" /></ObjectAnimationUsingKeyFrames></Storyboard></VisualState>
                  --></VisualStateGroup></VisualStateManager.VisualStateGroups><ContentPresenter Margin="4,0,0,0"
                              VerticalAlignment="Center"
                              HorizontalAlignment="Left"
                              RecognizesAccessKey="True" /></BulletDecorator><ControlTemplate.Triggers><Trigger Property="IsEnabled" Value="False"><Setter Property="Background" Value="{DynamicResource TransparentBrush}"/><Setter Property="BorderBrush" Value="{DynamicResource TransparentBrush}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style><SolidColorBrush x:Key="TransparentBrush" Color="#00000000" /></ResourceDictionary>


Binding and Converter via IValueConverter

$
0
0
I know that iin a binding you can use the property Converter to provide a specific converter class, inherited from IValueConverter, to it.
 
 My question is know, if it is somehow possible to create a user control like
public class MyTextBox : TextBox, IValueConverter
and assign this, i.e. the textbox itself, to the Converter property in the Binding expression.
Example:
<MyTextBox... Text="{Binding Path=Price, Mode=TwoWay, Converter={RelativeSource Self}}"... />

My goal is not to have a separate class for conversion but an extended textbox which can convert the values AND knows all members of MyTextBox (like a swing listener in java).

Thx a lot for your support.
 

How to use IsEnable based on 2 checkboxes

$
0
0

I have a WPF form with a textbox and 2 check boxes.

The textbox should be enabled if checkbox1 = false or checkbox1 = true and checkbox2 = true


I tried using MultiBinding and converters but checkbox1 can be true if checkbox2 = true.

Can I use a converter in this situation? How?

Threading Problem

$
0
0

I'm having a problem updating an Image control from another thread.  It gives me the error: " The calling thread cannot access this object because a different thread owns it."  Thanks in advance.

public MainWindow() { InitializeComponent(); cWindow.OnNewFrame += cWindow_OnNewFrame; cWindow.Open(camSource); } void cWindow_OnNewFrame(BitmapImage NewFrame) { //if (!NewFrame.Dispatcher.CheckAccess()) //I've tried both if (!imgFrames.Dispatcher.CheckAccess()) //I've tried both { this.imgFrames.Dispatcher.BeginInvoke(new ADT.Cameras.NewFrameEventHandler(cWindow_OnNewFrame), NewFrame); } else { //Error here imgFrames.Source = NewFrame; } } --------------------------------- public class WebSource : IDisposable, ICameraSource { public void Start() { ThreadPool.QueueUserWorkItem(new WaitCallback(tempThread_DoWork)); } void tempThread_DoWork(object sender) { BitmapImage bi = new BitmapImage(new Uri(@"C:\003.png")); while (true) { if (OnNewFrame != null) OnNewFrame(bi); System.Threading.Thread.Sleep(33); } } } -------------------------------- public class CameraWindow:IDisposable { public event NewFrameEventHandler OnNewFrame = null; private void HandleNewFrame(BitmapImage NewFrame) { calculateFPS(); if (OnNewFrame != null) OnNewFrame(NewFrame); }

 public void Open(string cameraSource)
        {
            if (localSource == null)
            {
                localSource = new WebSource();
                localSource.Source = cameraSource;
                localSource.OnNewFrame += HandleNewFrame;
                localSource.Start();
            }
        }

} ---------------------------- public delegate void NewFrameEventHandler(BitmapImage NewFrame);


WPF has lost its mind, Image has an image which I did not set

$
0
0

I was changing the XAML for a game I volunteered to write and just added an Image tag.  

<Image Grid.Column="0" ></Image>

Now that image has no name and no binding when I added it, but when I run the project to ensure I have the new format correct surprise surprise, it has an Image.  The image is a resource within the project but that image is in a folder within a folder in the project.  With no name it cannot be set in code and with no binding cannot be set by the datacontext.

 There is no default style set for Image so that cannot be it.

When I use Snoop it does have the source set.  I did not set it.  Confused as double hockey sticks.


Lloyd Sheen

How to Implement a Binding Converter

$
0
0

I am binding an instantiated class to a wpf window using binding converter classes.  I have all the parts in place but can't figure out how to bring them together.

My converter class sits in a module and is defined by:

Public Class DateStringConverter

The XAML in the window that uses this converter includes (non-essential parts omitted):

<Window
    x:Class="VehicleExpenses"
    xmlns:local="clr-namespace:PIM"<Window.Resources><local:DateStringConverter x:Key="DSC" /></Window.Resources><TextBox
	Text="{Binding Path=Charge, Mode=OneWayToSource, Converter={StaticResource DSC}}" /></Window>

The name of the application is PIM.  The error I'm getting is:

    The name "DateStringConverter" does not exist in the namespace "clr-namespace:PIM".

If I look in the object browser, the class "DateStringConverter" shows as a PIM resource.

So what am I doing wrong?

Viewing all 18858 articles
Browse latest View live


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