小编Dan*_*şar的帖子

WPF附加属性数据绑定

我尝试使用附加属性绑定.但无法让它发挥作用.

public class Attached
{
    public static DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("TestProperty", typeof(bool), typeof(Attached),
        new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits));

    public static bool GetTest(DependencyObject obj)
    {
        return (bool)obj.GetValue(TestProperty);
    }

    public static void SetTest(DependencyObject obj, bool value)
    {
        obj.SetValue(TestProperty, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML代码:

<Window ...>
    <StackPanel local:Attached.Test="true" x:Name="f">
        <CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}" />
        <CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay}" />
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

和绑定错误:

System.Windows.Data Error: 40 : BindingExpression path error: '(local:Attached.Test)' property not found on 'object' ''StackPanel' (Name='f')'. BindingExpression:Path=(local:Attached.Test); DataItem='StackPanel' (Name='f'); …
Run Code Online (Sandbox Code Playgroud)

wpf xaml binding attached-properties

63
推荐指数
2
解决办法
4万
查看次数

样式或资源中的WPF DataGrid列

是否可以DataGrid在样式或资源中声明列?我想做这样的事情:

<....Resources>
    <DataGridColumns x:Key="dgcDataGridColumns">
        <DataGridTextColumn />
        <DataGridTextColumn />
    </DataGridColumns
</....Resources>

<DataGrid Columns="{StaticResource dgcDataGridColumns}" />
Run Code Online (Sandbox Code Playgroud)

原因是我必须分享4种不同的列定义DataGrids.有没有办法实现这个目标?最好的是没有代码背后!

wpf resources datagrid

19
推荐指数
3
解决办法
2万
查看次数

结合扩展器和网格(可调整大小的扩展器)

我想要一个像可调整大小的扩展器.我的基本想法是这样的:

<Grid HorizontalAlignment="Left">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="2" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Expander Grid.Column="0" ExpandDirection="Right">
          ...
    </Expander>

    <GridSplitter Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />

    ...
</Grid>
Run Code Online (Sandbox Code Playgroud)

问题是:如果我移动网格分割器并折叠扩展器,我会得到一个很大的空白区域.如何使整个列崩溃?或者是否有另一种方法可以使扩展器"可调整大小"

wpf grid xaml expander gridsplitter

15
推荐指数
1
解决办法
3万
查看次数

动态创建基类的类型和调用构造函数

我需要动态创建一个类.大多数工作正常,但我坚持生成构造函数.

AssemblyBuilder _assemblyBuilder =
        AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("MyBuilder"),                                                        AssemblyBuilderAccess.Run);

ModuleBuilder _moduleBuilder = _assemblyBuilder.DefineDynamicModule("MyModule");

public static object GetInstance<TSource, TEventArgs>(this TSource source, string eventName)
    where TSource : class
{
    var typeName = "MyTypeName";
    var typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public);

    // create type like class MyClass : GenericType<MyClass, TSource, TEventArgs>
    var baseNotGenericType = typeof(GenericType<,,>);
    var baseType = baseNotGenericType.MakeGenericType(typeBuilder, typeof(TSource), typeof(TEventArgs)); 
    typeBuilder.SetParent(baseType);


    // the base class contains one constructor with string as param
    var baseCtor = baseNotGenericType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(string) }, null); …
Run Code Online (Sandbox Code Playgroud)

c# reflection reflection.emit ilgenerator

11
推荐指数
2
解决办法
1万
查看次数

Microsoft.ACE.OLEDB.12.0 CSV ConnectionString

我知道这种问题会不时被问到,但我找不到任何令人满意的解决方案.

如何使用MS ACE OLEDB 12打开CSV文件?我尝试使用以下代码.

DbConnection connection = new OleDbConnection();
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Documents;Extended Properties=\"Text;HDR=Yes\"";
connection.Open();
DbCommand cmd;

cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM [Mappe1#csv]";
DbDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    for (int i = 0; i < reader.FieldCount; i++)
        Console.Write("(" + reader.GetValue(i).ToString() + ")");

    Console.WriteLine();
}

cmd.Dispose();
connection.Dispose();
Console.WriteLine("Done");
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

问题是只找到一列.文本由';'分隔.即使我用"Delimited(|)"指定分隔符,它也行不通.

我找不到这个提供商的任何文档......

c# csv oledb provider connection-string

9
推荐指数
2
解决办法
4万
查看次数

c#System.Threading.Timer等待处理

我有一个使用Timer的类.这个类实现IDispose.我想在Dispose方法中等待,直到计时器不会再次触发.

我这样实现它:

private void TimerElapsed(object state)
{
    // do not execute the callback if one callback is still executing
    if (Interlocked.Exchange(ref _timerIsExecuting, 1) == 1) 
        return;

    try
    {
        _callback();
    }
    finally
    {
        Interlocked.Exchange(ref _timerIsExecuting, 0);
    }
}

public void Dispose()
{
    if (Interlocked.Exchange(ref _isDisposing, 1) == 1)
        return;

    _timer.Dispose();

    // wait until the callback is not executing anymore, if it was
    while (_timerIsExecuting == 0) 
    { }

    _callback = null;
}
Run Code Online (Sandbox Code Playgroud)

这个实现是否正确?我认为这主要取决于_ timerIsExecuting == 0是一个原子操作的问题.或者我必须使用 …

c# multithreading dispose timer

7
推荐指数
2
解决办法
7262
查看次数

匹配右括号的正则表达式不在引号中

我正在尝试构建一个匹配字符串的正则表达式

1.) $(Something)
2.) $(SomethingElse, ")")
3.) $(SomethingElse, $(SomethingMore), Bla)
4.) $$(NoMatch) <-- should not match
5.) $$$(ShouldMatch) <-- so basically $$ will produce $
Run Code Online (Sandbox Code Playgroud)

在文本中.

编辑:单词Something,SomethingElse,NoMatch,ShouldMatch甚至可以是其他单词 - 它们是宏的名称.我试图匹配的字符串是"宏调用",它可以出现在文本中,应该用它们的结果替换.我需要正则表达式只是为了语法高亮.应突出显示完整的宏调用.3号目前不是那么重要.需要1号和2号才能工作.如果数字4和5不能像上面所写的那样工作,但是$(在a之后的任何一个$都不匹配,那就没关系了.

目前我有

(?<!\$)+\$\(([^)]*)\)
Run Code Online (Sandbox Code Playgroud)

$(如果没有前导$,哪个匹配任何匹配,如果我找不到另一种方法来应用$$结构,这可能没问题.

我想要完成的下一步是忽略结束括号,如果它在引号中.我怎么能实现这个目标?

编辑所以,如果我有一个像这样的输入

Some text, doesn't matter what. And a $(MyMacro, ")") which will be replaced.
Run Code Online (Sandbox Code Playgroud)

完整'$(MyMacro, ")")'将突出显示.

我已经有了这个表达方式

"(?:\\\\|\\"|[^"])*"
Run Code Online (Sandbox Code Playgroud)

报价包括报价转义.但我不知道如何应用这种方式来忽略它们之间的一切......

PS我正在使用.NET来应用正则表达式.这样平衡的团体将得到支持.我只是不知道如何应用这一切.

.net regex

6
推荐指数
1
解决办法
1585
查看次数

C# 是否需要在 getter 和 setter 中锁定?

当多个线程将通过 get/set 函数访问属性/字段时,是否有必要锁定 getter 和 setter。

例如:

您有一个计时器,它可以定期获取对象的值。以及定期更新此值的过程。

public class Task : IProgressProvider
{
    ...
    public Progress GetProgress()
    {
        // should i lock here?
        return _progress;
    }

    public SetProgress(Progress progress)
    {
        // and lock here?
        _progress = progress;
    }

    public void Execute()
    {
        // ...
        SetProgress(new Progress(10));
        // ...
        SetProgress(new Progress(50));
        // ...
        SetProgress(new Progress(100));
    }
}

public class ProgressReporter
{
    public ProgressReporter()
    {
        _timer = new Timer();
        _timer.Elapsed += Elapsed;
        // ...
    }

    // ...

    public void Elapsed(...)
    { …
Run Code Online (Sandbox Code Playgroud)

c# multithreading locking properties volatile

5
推荐指数
1
解决办法
6747
查看次数

收集仍在范围内的对象 - GC.Collect

我读过这篇文章:http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx,老实说,我不了解每一个细节.据我所知,在下面的代码中,即使我没有将c设置为null,也应该收集c.另一件事是,只要我们处于相同功能的范围内,在foreach期间发生的分配似乎不会被释放.(见下面的例子)

class Program
{
    public class SomeClass
    {
        public byte[] X;

        public SomeClass()
        {
            X = new byte[1024 * 1024 * 100];
            X[155] = 10;
        }
    }

    static void Main()
    {
        Console.WriteLine("Memory: " + GC.GetTotalMemory(false));

        SomeClass c;
        c = new SomeClass();

        Console.WriteLine("Memory: " + GC.GetTotalMemory(false));
        GC.Collect();
        Console.WriteLine("Memory: " + GC.GetTotalMemory(true));
        Console.ReadKey();

        /*
         * Output:
         * 
         * Memory: 186836
         * Memory: 105044468
         * Memory: 104963676
         * 
         */
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑第一个示例的解决方案:调试模式(不在调试器中运行,但甚至在编译模式下运行).如果我使用Release它将按预期工作:即使没有设置为null也会收集c.对于第二个例子,同样适用.

第二个例子

static void Main(string[] args)
{ …
Run Code Online (Sandbox Code Playgroud)

.net c# garbage-collection

4
推荐指数
1
解决办法
942
查看次数

c#:写v1的方法比较短!?v2:!v2

我能写吗?

bool v1, v2;
// ...
Run Code Online (Sandbox Code Playgroud)

编辑:我很抱歉这些混乱.正确的陈述应该是:

bool v3 = !v1 ? v2 : !v2;
Run Code Online (Sandbox Code Playgroud)

原来我问了

bool v3 = v1 ? v2 : !v2;
Run Code Online (Sandbox Code Playgroud)

更短?或者:是否有一个具有相同结果的运算符?

因此我将Anders Abels的回答标记为正确,因为他回答了我的初步问题.我只需要反驳他的答案.

c# syntax boolean

4
推荐指数
1
解决办法
205
查看次数

游戏中流畅的动画

如何创建"平滑"动画?我正在开发一款关于android的游戏.我知道做平滑动画的默认方式不是最好的:

perFrame() {
    time = highrestime();
    frameTime = time - lastTime;
    lastTime = time;

    // now you could use frameTime as delta. this will lead to not real
    // smooth animations
}
Run Code Online (Sandbox Code Playgroud)

我读了一些关于这个主题的文件.特别是如果你使用物理模拟.着名文章似乎是这样的:http://gafferongames.com/game-physics/fix-your-timestep/ 我创建了一个基本类,如下所示:

public class TimeSystem {
private long mCurrentTime;
private long mAccumulator;
private Simulation mSimulation; 
private Renderer mRenderer;

private static float mSimulationDelta = 1000f / 60f;

public TimeSystem(Simulation simulation, Renderer renderer) {
    mCurrentTime = System.currentTimeMillis();
    mAccumulator = 0;

    mSimulation = simulation;
    mRenderer = renderer;
} …
Run Code Online (Sandbox Code Playgroud)

animation frame-rate smooth

3
推荐指数
1
解决办法
2469
查看次数

.NET应用程序的本机访问冲突

我们遇到.NET应用程序的问题.它在关闭时随机产生本机访问冲突(因此不是.NET异常).

  • Windows Server 2012 x64(在刀片系统上运行的虚拟机)
  • .NET 4.0 Framework(已安装4.5)
  • 我们的应用程序是.NET x86应用程序(不是AnyCPU;不是ASP.NET)
  • 第三方本机模块使用SQL CE 3.5等

来自Windows事件日志的错误报告看起来像这样(省略了应用程序和模块名称,我从德语翻译了条目):

Exceptioncode: 0xc0000005
Offset: 0x00006a9e
Process ID: 0xfe8
...
Run Code Online (Sandbox Code Playgroud)

我发现0xc0000005是一种访问冲突.由于.NET NullReferenceException,也可能发生这种情况.当Windows错误报告对话框打开时,我们已经使用ProcDump标志-ma 创建了一个完整的内存转储.

当我打开这个转储时,除了.exe文件本身之外,我找不到任何加载的.NET模块.我不是本地编程方面的专家,只知道一些关于WinDbg的基础知识.

所以我做了什么:

  1. 使用WinDbg打开转储
  2. 使用设置符号路径

    .sympath SRV*C:\Symbols*http://msdl.microsoft.com/download/symbols;C:\PathToMatchingPDBs\ForTheProgram
    
    Run Code Online (Sandbox Code Playgroud)
  3. 重新加载所有符号

    .reload /d /f
    
    Reloading current modules
    ...*** ERROR: Symbol file could not be found.  Defaulted to export symbols for sysfer.dll - 
    ...
    
    Run Code Online (Sandbox Code Playgroud)
  4. ~* k 输出

    .  0  Id: 1560.19a4 Suspend: 0 Teb: ff20e000 Unfrozen
    ChildEBP RetAddr  
    0058f0e8 7744c752 ntdll!ZwWaitForMultipleObjects+0xc
    0058f26c 76d256c0 KERNELBASE!WaitForMultipleObjectsEx+0x10b
    0058f2e0 76d2586a kernel32!WerpReportFaultInternal+0x1c4
    0058f2f4 …
    Run Code Online (Sandbox Code Playgroud)

.net il memory-dump windbg access-violation

3
推荐指数
1
解决办法
2103
查看次数

WPF TreeViewItem背景

当(或应用程序)失去焦点时,如何更改Background选定对象TreeViewItemTreeView。默认情况下,所选项目的背景为浅灰色。

编辑:第一个答案后尝试:但是TargetName="Bd"找不到元素。

<TreeView>
        <TreeView.Resources>
            <Style x:Key="{x:Type TreeViewItem}" TargetType="{x:Type TreeViewItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TreeViewItem}">
                            <ControlTemplate.Triggers>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="IsSelected" Value="True"/>
                                        <Condition Property="IsSelectionActive" Value="False"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
                                </MultiTrigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>

        <TreeViewItem Header="Test1" IsExpanded="True">
            <TreeViewItem Header="Test2" />
            <TreeViewItem Header="Test3" />
            <TreeViewItem Header="Test4" />
            <TreeViewItem Header="Test5" />
        </TreeViewItem>
    </TreeView>
Run Code Online (Sandbox Code Playgroud)

wpf background focus treeviewitem

2
推荐指数
1
解决办法
1万
查看次数