我是新來WPF和數據綁定,所以我可能很容易錯過我的研究中的東西,或者我一直在使用錯誤的搜索條件(更可能)找到解決方案。WPF MultiValueConverter數據綁定到字符串值不參考
綁定的值似乎越來越被傳遞,而不是對象的引用,所以當值在後面的代碼中設置時不會被更新。
試圖概括一個OpenFileDialog在選項卡控件的某些不同選項卡上有用。我創建保存的參數自定義數據對象(路徑,過濾器,和TextBox)
class OpenFileCommandParameters
{
public string Filter { get; set; }
public string Path { get; set; }
public string TextBox { get; set; }
}
class OpenFileCommandParamtersConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
OpenFileCommandParameters parameters = new OpenFileCommandParameters();
if (values[0] is string) parameters.Filter = (string)values[0];
if (values[1] is string) parameters.Path = (string)values[1];
if (values[2] is string) parameters.TextBox = (string)values[2];
return parameters;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
的XAML傳遞的信息是這樣的:
<TextBox Name="ButtonTagImportFileName" Text="{Binding Path=TagImportTabVM.TbFileName}" Height="23" HorizontalAlignment="Left" Margin="83,17,0,0" VerticalAlignment="Top" Width="221" />
<Button Name="TagImportOpenFile" Content="Open File" Command="{Binding Path=OpenFileCommand}" Height="23" HorizontalAlignment="Left" Margin="342,17,0,0" VerticalAlignment="Top" Width="98" >
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource openFileCommandParametersConverter}">
<MultiBinding.Bindings>
<Binding Source="XML files (*.xml)|*xml|All files (*.*)|*.*"/>
<Binding Path="AppPath"/>
<Binding Path="TagImportTabVM.TbFileName"/>
</MultiBinding.Bindings>
</MultiBinding>
</Button.CommandParameter>
兩個文本框和打開文件按鈕具有綁定到相同的字符串屬性。
的屬性,都會通過命令
private void OpenFile(object parameter)
{
var parameters = parameter as OpenFileCommandParameters;
FileDialog.Filter = parameters.Filter;
FileDialog.InitialDirectory = parameters.Path;
if (parameters == null) return;
var result = FileDialog.ShowDialog();
if (result == true)
{
parameters.TextBox = FileDialog.SafeFileName;
}
}
一旦該命令完成,我希望TbFileName的價值是一樣的,從文件對話框什麼來執行更新。不是這種情況。如從OpenFile塊結束之前的中斷點看到的那樣。
我很感謝你能提供給我任何幫助。