1

コンテキストを与えるには:アイテムのリストがあり、それぞれの画像を描画します。それらはすべて黒い境界線を持っていますが、これは特定の「ブラシ」プロパティと同じオブジェクトにバインドされています。そのブラシには、どのブラシが選択されているかを示す赤い境界線があります。

ここにコードがあります

<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Border BorderBrush="Black"
                BorderThickness="2 2 2 2">
            <Border.Style>
                <Style TargetType="{x:Type Border}">
                    <Style.Triggers>
                        <DataTrigger Value="True">
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource ResourceKey=AreEqualConverter}">
                                    <Binding/>
                                    <Binding ElementName="Me" Path="Brush"/>
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <Setter Property="BorderBrush" Value="Red"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <Image Source="{Binding}" 
                   Height="{Binding ElementName=TilePreviewSize, Path=Value}"
                   Width="{Binding ElementName=TilePreviewSize, Path=Value}"
                   RenderOptions.BitmapScalingMode="NearestNeighbor"
                   MouseDown="OnBrushMouseDown"/>
        </Border>
    </DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

「NullReferenceException : オブジェクト参照がオブジェクトのインスタンスに設定されていません」というエラーが表示されます。次のコード ブロックのコメントが解除されたとき。何が問題なのかわかりません。

<Style TargetType="{x:Type Border}">
    <Style.Triggers>
        <DataTrigger Value="True">
            <DataTrigger.Binding>
                <MultiBinding Converter="{StaticResource ResourceKey=AreEqualConverter}">
                    <Binding/>
                    <Binding ElementName="Me" Path="Brush"/>
                </MultiBinding>
            </DataTrigger.Binding>
            <Setter Property="BorderBrush" Value="Red"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

コンバーターのコードを見たい場合は、ここにあります(非常に簡単です)

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (values.Length < 2)
        throw new NotSupportedException();

    var obj = values[0];

    for (int i = 1; i < values.Length; ++i)
        if (!values[i].Equals(obj))
            return false;

    return true;
}

スタックトレースまたはエラーは次のとおりです。

   at IntegratorUI.Contexts.RoomContext.System.Windows.Markup.IStyleConnector.Connect(Int32 connectionId, Object target) in [...] line 138
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.StackPanel.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run()
   at IntegratorUI.App.Main() in D:\trollmeme\integrator\IntegratorUI\obj\Debug\App.g.cs:line 0
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

これを整理するのを手伝ってくれてありがとう!

ニック

4

2 に答える 2

2

配列内の値の一部を にすることができますnull。静的Equalsメソッドを使用します。objが null でないことを確認することも賢明です。

if (!Object.Equals(values[i], obj))

アップデート

スタック トレースを確認したところ、問題はこの問題に関連しているようです。ネストされたテンプレート/スタイルを使用すると思われます。これは .NET 4 に影響し、.NET 4.5 で修正されたようです。推奨される回避策は、スタイルをリソースとして参照することです。

<UserControl.Resources>
   <Style x:Key="MyBorder" TargetType="{x:Type Border}" ...
</UserControl.Resources>

<DataTemplate>
    <Border BorderBrush="Black"
            BorderThickness="2 2 2 2"
            Style="{StaticResource MyBorder}" ...
</DataTemplate>

全体ItemsControlが別のテンプレート内にネストされている場合は、おそらくそれらすべてのテンプレートをリソースに移動する必要があることに注意してください。

于 2013-10-23T21:24:28.563 に答える
1

あなたの問題は、 のMouseDown="OnBrushMouseDown";内部でハンドラーを定義したことですDataTemplate。したがって、MouseButtonEventHandler を正しく取得できません。

この問題を解決するには、 style のリソース ディクショナリに新しい Style を追加します。

<Style x:Key="MouseDownHandlerStyle" TargetType="{x:Type Image}">
    <EventSetter Event="MouseDown" Handler="OnBrushMouseDown"/>
</Style>

乾杯!

于 2013-10-24T05:24:20.060 に答える